Find first occurence numerical position in a string by php
This question already has an answer here:
最简单的方法是使用preg_match()标志PREG_OFFSET_CAPTURE恕我直言
$string = 'abc2.mp3';
if(preg_match('/[0-9]/', $string, $matches, PREG_OFFSET_CAPTURE)) {
echo "Match at position " . $matches[0][1];
} else {
echo "No match";
}
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;
}
链接地址: http://www.djcxy.com/p/13134.html
上一篇: 使用PHP中的正则表达式在String中搜索和提取
下一篇: 通过php查找字符串中的第一个数字位置