2012-01-10 47 views

回答

0
function searchPositions($text, $needle = ''){ 
    $positions = array(); 
    for($i = 0; $i < strlen($text);$i++){ 
     if($text[$i] == $needle){ 
      $positions[] = $i; 
     } 
    } 
    return $positions; 
} 

print_r(searchPositions('Hello world!', 'o')); 

會做。

1

在PHP中沒有這樣的功能存在(據我所知),做你要找的是什麼,但你可以利用preg_match_all得到一個子模式的偏移:

$str = "hello world"; 

$r = preg_match_all('/o/', $str, $matches, PREG_OFFSET_CAPTURE); 
foreach($matches[0] as &$match) $match = $match[1]; 
list($matches) = $matches; 
unset($match); 

var_dump($matches); 

輸出:

array(2) { 
    [0]=> 
    int(4) 
    [1]=> 
    int(7) 
} 

Demo

9

沒有循環需要

$str = 'Hello World'; 
$letter='o'; 
$letterPositions = array_keys(array_intersect(str_split($str),array($letter))); 

var_dump($letterPositions); 
+0

+1不錯,要得到更流利的這些數組函數。 – hakre 2012-01-10 07:53:46

相關問題