Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

strpos

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.

like image 681
CKH Avatar asked Jan 07 '16 12:01

CKH


1 Answers

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";
}
like image 164
maxhb Avatar answered Nov 15 '22 00:11

maxhb