Find first occurence numerical position in a string by php [duplicate]
Asked Answered
N

2

8

May I ask how to find a first occurrence numerical position in a string with PHP? For example, if "abc2.mp3" is a string, return a value of 3 since position of the first occurrence number "2" in "abc2.mp3" is 3 (the first position is 0).

I used strpos() function in PHP, it only returns whether the string is number or not, i.e. TRUE or FALSE.

Thanks for your reply.

Niddering answered 7/1, 2016 at 12:20 Comment(2)
can you show us ur real exmple? i'm almost certain strpos is working as it intendedDismay
Dear Ben Pearl Kahan, Rizier123, I think my question is different from previous ones because it is used to find a non-specific first occurence numerical stringNiddering
R
2

Easiest way is using preg_match() with flag PREG_OFFSET_CAPTURE IMHO

$string = 'abc2.mp3';
if(preg_match('/[0-9]/', $string, $matches, PREG_OFFSET_CAPTURE)) {
  echo "Match at position " . $matches[0][1];
} else {
  echo "No match";
}
Regnal answered 7/1, 2016 at 12:35 Comment(2)
May I ask what does '$matches[0][1]' in the code mean?Niddering
$matches is an array containing one array for each match of the regex. Each of those arrays has an entry [0] which holds the matching text and an entry [1] which holds the position of the match. Just do ` var_dump($matches)` to see it in action. So ` $matches[0][1]` is the position of the first match.Regnal
L
0

strpos() is the PHP function you are looking for. This function returns FALSE when the string is not found, that's why you might be confused.

From the PHP documentation:

Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

Edit:

You could use regex with preg_match(). This function should do the trick:

function getFirstNumberOffset($string){
    preg_match('/^\D*(?=\d)/', $string, $m);
    return isset($m[0]) ? strlen($m[0]) : FALSE;
}
Linders answered 7/1, 2016 at 12:24 Comment(4)
Thanks. But how do I find the numerical value in a string then?Niddering
@Niddering What input do you have and what output do you want? Your description is very vague.Linders
I may ask it in a good way. It is to find the first occurence numerical position in a stringNiddering
That's better, thanks! I updated my post with a working function.Linders

© 2022 - 2024 — McMap. All rights reserved.