Check if a String Ends with a Number in PHP

后端 未结 3 1316
不思量自难忘°
不思量自难忘° 2020-12-11 03:09

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($stri         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 03:51

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

提交回复
热议问题