Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a String Ends with a Number in PHP

I'm trying to implement the function below. Would it be best to use some type of regex here? I need to capture the number too.

function endsWithNumber($string) {
  $endsWithNumber = false;

  // Logic

  return $endsWithNumber;
}
like image 353
Kirk Ouimet Avatar asked Nov 06 '10 18:11

Kirk Ouimet


3 Answers

To avoid potential undefined index error use

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

instead.

like image 79
Nanaki Avatar answered Oct 14 '22 11:10

Nanaki


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.

like image 20
Reese Moore Avatar answered Oct 14 '22 09:10

Reese Moore


$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 .*

like image 7
Kinjal Dixit Avatar answered Oct 14 '22 09:10

Kinjal Dixit