将长字符串转换为数组和索引

时间:2015-12-09 21:16:57

标签: php

如果我们的字符串变量如下:

$str = "This is test text and I'd like to split it";

如何让它在foreachfor循环中将每个特定单词打印为数组项,因此数组看起来像([0] => This,[1] =>是...)

谢谢!

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
相关问题