Check if line with number ends in PHP

I am trying to implement this function below. Would it be better to use some type of regex here? I also need to fix the number.

function endsWithNumber($string) { $endsWithNumber = false; // Logic return $endsWithNumber; } 
+6
string php numbers
source share
3 answers
 $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]; } 

regex is explained as follows:

. *? - it will take all the characters in the string from the beginning until a match is found for the next part.

(\ d +) $ - this is one or more digits to the end of the line, grouped.

without? in the first part, only the second digit will correspond in the second part, because all the numbers in front of it will be occupied. *

+7
source share

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

This only checks if the last character in the string is numeric, if you want to catch and return multiple-valued numbers, you may have to use a regular expression.

The corresponding regular expression will be /[0-9]+$/ , which will capture the number line if it is at the end of the line.

+19
source share

in my opinion. A simple way to find a string ends with a number

 $length=strlen("string1")-1; if(is_numeric($string[$length])) { echo "String Ends with Number"; } 
+1
source share

All Articles