将句子分成用逗号分隔的单词

时间:2012-06-06 14:52:31

标签: php

我在数据库字段中保存了一个句子,我希望用单词打破它,但是这些单词需要用昏迷分隔,如下所示:

This, is, test, text

我尝试使用explode(),但它没有完成工作。

3 个答案:

答案 0 :(得分:4)

你可以做到

$text = "This is test text";
echo str_replace (" ", ", ", $text); // This, is, test, text

答案 1 :(得分:3)

你可以preg_split()根据中间至少一个空格来分割单词(尽管带有周围空格的感叹号也会被视为单词);然后你把它们粘在一起。

echo join(', ', preg_split('/\s+/', $str));

或者,让wordwrap为你完成工作,装饰和不装饰:

echo join(', ', explode("\0", wordwrap($s, 1, "\0")));

答案 2 :(得分:1)

我知道这不是最有效的方式,但如果你想使用爆炸,你还需要使用内爆:

<?php

$foo = 'this is a test';
$bar = implode(', ', explode(' ', $foo));
print_r($bar);

?>

会显示:this, is, a, test

相关问题