我需要以数组的形式获取字符串中字符的所有位置。我知道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"
问题:什么循环可以帮助我构建一个可以帮助我实现所需输出的功能?
答案 0 :(得分:1)
无需循环
$str = 'australia';
$letter='a';
$letterPositions = array_keys(
array_intersect(
str_split($str),
array($letter)
)
);
var_dump($letterPositions);
答案 1 :(得分: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
)
*/