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;
}
}
}
Another way to do it: $text = "1 out of 23"; preg_match('/(\d+)\D*$/', $text, $m); $lastnum = $m[1]; This will match last number from the string even if it is followed by non digit.
The strrpos() is an in-built function of PHP which is used to find the position of the last occurrence of a substring inside another string.
strrpos() Function: This inbuilt function in PHP is used to find the last position of string in original or in another string. It returns the integer value corresponding to position of last occurrence of the string, also it treats uppercase and lowercase characters uniquely.
You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With