PHP Regex to match the last occurrence of a string

时光总嘲笑我的痴心妄想 提交于 2020-01-13 13:11:06

问题


My string is $text1 = 'A373R12345'
I want to find last none digital number occurrence of this string.
So I use this regular expression ^(.*)[^0-9]([^-]*)
Then I got this result:
1.A373
2.12345

But my expected result is:
1.A373R
(It has 'R')
2.12345

Another example is $text1 = 'A373R+12345'
Then I got this result:
1.A373R
2.12345

But my expected result is:
1.A373R+
(It has '+')
2.12345

I want contain the last none digital number!!
Please help !! thanks!!


回答1:


$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

Explanation of regex broken down:

^ 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



来源:https://stackoverflow.com/questions/13618077/php-regex-to-match-the-last-occurrence-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!