PHP Regex匹配最后一次出现的字符串

时间:2012-11-29 02:52:11

标签: php regex preg-match preg-split

我的字符串是$text1 = 'A373R12345'
我想找到这个字符串的最后没有数字编号。
所以我使用这个正则表达式^(.*)[^0-9]([^-]*)
然后我得到了这个结果:
1.A373
2.12345

但我的预期结果是:
1.A373R
(它有'R')
2.12345

另一个例子是$text1 = 'A373R+12345'
然后我得到了这个结果:
1.A373R
2.12345

但我的预期结果是:
1.A373R +
(它有'+')
2.12345

我想包含最后一个没有数字的号码!!
请帮忙 !!谢谢!

1 个答案:

答案 0 :(得分:7)

$text1 = 'A373R12345';
preg_match('/^(.*[^\d])(\d+)$/', $text1, $match);
echo $match[1]; // A373R
echo $match[2]; // 12345

$text1 = 'A373R+12345';
preg_match('/^(.*[^\d])(\d+)$/', $text1, $match);
echo $match[1]; // A373R+
echo $match[2]; // 12345

正则表达式的解释:

^ match from start of string
(.*[^\d]) match any amount of characters where the last character is not a digit 
(\d+)$ match any digit character until end of string

enter image description here

相关问题