简体   繁体   中英

PHP Position of Last Digit in a String

Looking 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 does it but I'm looking for the fastest way to do it (eg. 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;
        }
    }

}

you can find the final portion of the string with no numbers, count it, then subtract that 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]);
}

You can use PREG_OFFSET_CAPTURE flag with preg_match to capture indexes 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

Try this not a reg but should work could pop in in a ternary statement if you needed to save space.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM