[ACCEPTED]-Check if a String Ends with a Number in PHP-numbers

Accepted answer
Score: 29

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

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

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

Score: 7
$r = preg_match_all("/.*?(\d+)$/", $test, $matches);
//echo $r;
if($r>0) {
    echo $matches[count($matches)-1][0];

the regex is explained as follows:

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

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

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

Score: 2

To avoid potential undefined index error 1 use

is_numeric($code[strlen($code) - 1])


Score: 1

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

    $string = "string1";
    $length = strlen($string)-1;
       echo "String Ends with Number";
Score: 0

Firstly, Take the length of string, and check if 4 it is equal to zero (empty) then return false. Secondly, check with 3 built-in function on the last character 2 $len-1.

is_numeric(var) returns boolean whether a variable is 1 a numeric string or not.

function endsWithNumber($string){
    $len = strlen($string);
    if($len === 0){
        return false;
    return is_numeric($string[$len-1]);




Score: 0

This should work

function startsWithNumber(string $input):bool
      $out = false; //assume negative response, to avoid using else
      if(strlen($input)) {
        $out = is_numeric($input[0]); //only if string is not empty, do this to avoid index related errors.
      return $out;


More Related questions