是否有一个就绪函数来获取位置数组,其中某个子字符串开始了?
例如,
$needle = "apple";
$haystack = "one apple two apples three apples";
$r = f($haystack , $needle);
// should give:
$r = array(4 , 13 , 24);
// i.e. the positions of "a" letters
我知道substr_count给出了子串的数量,但我怎样才能获得起始位置?
感谢您的帮助!
答案 0 :(得分:1)
$needle = "apple";
$haystack = "one apple two apples three apples";
$count = preg_match_all(
'/'.preg_quote($needle).'/',
$haystack, $matches,
PREG_OFFSET_CAPTURE
);
if ($count) {
var_dump($matches[0]);
}
如果你有PHP 5.5+,你可以使用数组列来轻松获得$ matches的所有偏移
var_dump(array_column($matches[0], 1));