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"

问题:什么循环可以帮助我构建一个可以帮助我实现所需输出的函数?

4

2 回答 2

1

无需循环

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

var_dump($letterPositions);
于 2013-03-07T12:04:55.990 回答
1

您可以使用 afor来循环该字符串:

$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
)
*/

键盘示例

于 2013-03-07T12:08:09.353 回答