2014-02-19 39 views
1

是否有準備好的函數來獲取位置數組,其中某個子字符串開始?如何獲取PHP中所有子字符串出現的起始位置?

例如,

$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給人子的數目,但我怎麼能得到的起始位置?

感謝您的幫助!

回答

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+,你可以使用數組列來獲取所有從$偏移容易匹配

var_dump(array_column($matches[0], 1)); 
相關問題