如果我们的字符串变量如下:
$str = "This is test text and I'd like to split it";
如何让它在foreach
或for
循环中将每个特定单词打印为数组项,因此数组看起来像([0] => This,[1] =>是...)
谢谢!
答案 0 :(得分:1)
您可以使用explode()
功能,如下所示:
<?php
$str = "This is test text and I'd like to split it";
$array = explode(" ", $str);
foreach($array as $key => $value){
echo $key . " => " . $value . "<br />";
}
?>
输出:
0 => This
1 => is
2 => test
3 => text
4 => and
5 => I'd
6 => like
7 => to
8 => split
9 => it
<强>编辑:强>
如果您只想打印一定数量的元素,请使用for
代替foreach
。
<?php
$str = "This is test text and I'd like to split it";
$array = explode(" ", $str);
for($i = 0; $i < 3; ++$i){
echo $i . "=>" . $array[$i] . "<br />";
}
?>
输出:
0=>This
1=>is
2=>test