2013-03-07 160 views
0

我需要以字符串形式獲取字符中所有位置的數組。我知道PHP函數strpos(),但它不接受數組作爲參數。在構建邏輯時需要幫助

這是必需的:

$name = "australia";   //string that needs to be searched 
$positions_to_find_for = "a"; // Find all positions of character "a" in an array 
$positions_array = [0,5,8];  // This should be the output that says character "a" comes at positions 0, 5 and 8 in string "australia" 

問:什麼迴路可以幫助我建立一個功能,可以幫助我實現所需的輸出?

+2

但你不發送一個數組作爲參數。 – 2013-03-07 12:04:27

+0

Mihai是對的,PHP字符串是*不是*數組。 – Fabien 2013-03-07 12:06:28

+0

我不認爲其他建議。他要求一個「strpos」變體,它返回所有出現針的位置,而不僅僅是第一個。這是一個很好的問題。 – MichaelRushton 2013-03-07 12:08:09

回答

1

可以使用for循環該字符串:

$name = "australia"; 
$container = array(); 
$search = 'a'; 
for($i=0; $i<strlen($name); $i++){ 
    if($name[$i] == $search) $container[] = $i; 
} 

print_r($container); 

/* 
Array 
(
    [0] => 0 
    [1] => 5 
    [2] => 8 
) 
*/ 

Codepad Example

+0

@Minhai lorga非常感謝你的朋友,不知道它不是太簡單...我是新來的編程,所以我發現很難建立這樣的邏輯。 – Mark 2013-03-07 12:19:52

1

沒有循環必要

$str = 'australia'; 
$letter='a'; 
$letterPositions = array_keys(
    array_intersect(
     str_split($str), 
     array($letter) 
    ) 
); 

var_dump($letterPositions);