2012-07-17 74 views
0

所以我有一個字符串,如下所示正則表達式找到最後一個項目名稱

Continent | Country | Region | State | Area | Town 

有時候字符串是

Continent | Country | Region | State | Area 

什麼是正則表達式抓住最後一項(即要麼城或區域)?

乾杯

回答

4

不需要正則表達式!

$str = 'Continent|Country|Region|State|Area'; 

$exp = explode('|', $str); 

echo end($exp); 
+0

+1因爲有相同的答案快7秒。 – 2012-07-17 01:41:17

+0

非常感謝! – Franco 2012-07-17 01:43:04

1

我不會用這個正則表達式的時候就可以達到同樣的用PHP string functions

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

以防萬一有人不想要的正則表達式(也去除了前面的空格):

$string = 'Continent | Country | Region | State | Area | Town'; 

preg_match('/[^|\s]+$/', $string, $last); 
echo $last; 
1

這是另一種解決方案。

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

請注意,這隻適用於有多個項目或strrchr將返回false。