且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查字符串是否以 PHP 中的数字结尾

更新时间:2023-02-11 15:55:01

$test="abc123";
//$test="abc123n";
$r = preg_match_all("/.*?(d+)$/", $test, $matches);
//echo $r;
//print_r($matches);
if($r>0) {
    echo $matches[count($matches)-1][0];
}

正则表达式解释如下:

.*?- 这将从一开始就占用字符串中的所有字符,直到也找到后续部分的匹配项.

.*? - this will take up all the characters in the string from the start up until a match for the subsequent part is also found.

(d+)$ - 直到字符串末尾的一位或多位数字,已分组.

(d+)$ - this is one or more digits up until the end of the string, grouped.

没有 ?在第一部分中,只有最后一个数字将在第二部分中匹配,因为它之前的所有数字都会被 .* 占用.*

without the ? in the first part, only the last digit will be matched in the second part because all digits before it would be taken up by the .*