用于查找最后一个项名称的正则表达式


Regular expression to find last item name

所以我有一个字符串,如下

Continent | Country | Region | State | Area | Town

有时字符串是

Continent | Country | Region | State | Area

获取最后一个条目(即Town或Area)的正则表达式是什么?

干杯

不需要正则表达式!

$str = 'Continent|Country|Region|State|Area';
$exp = explode('|', $str);
echo end($exp);

万一有人想要regex(也删除前面的空格):

$string = 'Continent | Country | Region | State | Area | Town';
preg_match('/[^|'s]+$/', $string, $last);
echo $last;

当您可以用PHP字符串函数实现以下功能时,我不会使用正则表达式:

$segments = explode(' | ', 'Continent | Country | Region | State | Area | Town');
echo end($segments);

这里是另一个解决方案。

$str = 'Continent|Country|Region|State|Area';
$last = substr(strrchr($str,'|'),1);

请注意,只有当存在多个项目或strrchr将返回false时,这才有效。