如何将句子切成单词并列出每个单词的索引?

时间:2017-05-31 03:50:42

标签: php string

我真的需要帮助。我真的很抱歉,因为我是PHP编码的初学者。 我想剪切一个句子中的每个单词,并列出每个单词的索引。

例句:

I want buy a new shoes this weekend.

我希望我的输出像这样:

[0] I , [1] want, [2] buy, [3] a, [4] new, [5] shoes, [6] this, [7] weekend

我将如何在PHP中完成此任务?

谢谢。

2 个答案:

答案 0 :(得分:1)

我希望这能回应你的问题

print_r(explode(" ", "I want buy a new shoes this weekend."));

Array
(
    [0] => I
    [1] => want
    [2] => buy
    [3] => a
    [4] => new
    [5] => shoes
    [6] => this
    [7] => weekend.
)

答案 1 :(得分:1)

你可以使用php split()

$text = "I want buy a new shoes this weekend";
$words = explode(" ", $text);
print_r($words);

这将提供以下输出。

Array
(
[0] => I
[1] => want
[2] => buy
[3] => a
[4] => new
[5] => shoes
[6] => this
[7] => weekend