Check if a String Ends with a Number in PHP

给你一囗甜甜゛ 提交于 2019-11-28 12:10:41
$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];
}

the regex is explained as follows:

.*? - 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+)$ - 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 .*

return is_numeric(substr($string, -1, 1));

This only checks to see if the last character in the string is numerical, if you want to catch and return multidigit numbers, you might have to use a regex.

An appropriate regex would be /[0-9]+$/ which will grab a numerical string if it is at the end of a line.

in my opinion The simple way to find a string ends with number is

$length=strlen("string1")-1;
if(is_numeric($string[$length]))
{
   echo "String Ends with Number";
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!