如何获取PHP中所有子字符串的起始位置?

如何获取PHP中所有子字符串的起始位置?,php,arrays,substr,substring,Php,Arrays,Substr,Substring,是否有一个ready函数来获取位置数组,即某个子字符串的起始位置 比如说, $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给出了子字符串的数量,但是我如何才能得到

是否有一个ready函数来获取位置数组,即某个子字符串的起始位置

比如说,

$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给出了子字符串的数量,但是我如何才能得到起始位置

谢谢你的帮助

$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]);
}
如果您有PHP5.5+,那么可以使用数组列轻松获取$matches的所有偏移量

var_dump(array_column($matches[0], 1));