PHP正则表达式匹配最后一个字符串的出现

4

我的字符串是 $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个回答

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


它在我的情况下运行良好!谢谢! 你能为我解释一下正则表达式吗?我只知道.* [^\d] 表示你想找到最后一个非数字的数字。 - Nick Hung
@crypticツ 你用了什么工具? - Epoc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接