Search code examples
phpstringstrpos

Find first occurence numerical position in a string by php


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.


Solution

  • 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";
    }