PHP position of the last digit in a string

Search for some regex to return the position of the last numeric digit of a string

$str = '1h 43 dw1r2 ow';  //Should return 10
$str = '24 h382';  //Should return 6
$str = '2342645634';  //Should return 9
$str = 'Hello 48 and good3 58 see you';  //Should return 20

This happens, but I'm looking for the fastest way to do this (e.g. regex?)

function funcGetLastDigitPos($str){

    $arrB = str_split($str);

    for($k = count($arrB); $k >= 0; $k--){

        $value =    $arrB[$k];
        $isNumber = is_numeric($value);

        //IF numeric...
        if($isNumber) {

            return $k;
            break;
        }
    }

}
+4
source share
3 answers

you can find the end of a string without numbers, count it, and then subtract from the length of the entire string.

$str = '1h 43 dw1r2 ow';  //Should return 10
echo lastNumPos($str); //prints 10
$str = '24 h382';  //Should return 6
echo lastNumPos($str); //prints 6
$str = '2342645634';  //Should return 9
echo lastNumPos($str);//prints  9
$str = 'Hello 48 and good3 58 see you';  //Should return 20
echo lastNumPos($str); //prints 20


function lastNumPos($string){
    //add error testing here

    preg_match('{[0-9]([^0-9]*)$}', $string, $matches);
    return strlen($string) - strlen($matches[0]);
}
+5
source

You can use the PREG_OFFSET_CAPTURE flag with preg_match to capture indices along with matches.

$str = 'Hello 48 and good3 58 see you';
$index = -1;
if(preg_match("#\d\D*$#", $str, $matches, PREG_OFFSET_CAPTURE)) {
    $index = $matches[0][1];
}

echo $index; //returns index if there is a match.. else -1

See working demo

+3
source

Try this not reg, but the work should appear in triple terms if you need to save space.

$a=is_numeric(substr($str, -1));
if($a){
    $k=substr($str, -1);
}else{
    $k='';
}
echo $k;
0
source

All Articles