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.

CKH
  • 133
  • 9
  • can you show us ur real exmple? i'm almost certain `strpos` is working as it intended – Andrew Jan 07 '16 at 12:24
  • 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 string – CKH Jan 07 '16 at 15:51

2 Answers2

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";
}
maxhb
  • 8,554
  • 9
  • 29
  • 53
  • May I ask what does '$matches[0][1]' in the code mean? – CKH Jan 07 '16 at 12:37
  • $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. – maxhb Jan 07 '16 at 12:52
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;
}
Rein
  • 3,211
  • 3
  • 16
  • 21