如何将一个句子转换为单词数组?

10

从这个字符串开始:

$input = "Some terms with spaces between";

我该如何生成这个数组?

$output = ['Some', 'terms', 'with', 'spaces', 'between'];
5个回答

31
你可以使用 explodesplit 或者 preg_splitexplode 使用固定的字符串拆分。
$parts = explode(' ', $string);

splitpreg_split使用正则表达式:

$parts = split(' +', $string);
$parts = preg_split('/ +/', $string);

基于正则表达式的分割下面是一个有用的示例:

$string = 'foo   bar';  // multiple spaces
var_dump(explode(' ', $string));
var_dump(split(' +', $string));
var_dump(preg_split('/ +/', $string));

9
在PHP 5.3中,split函数已被弃用,因此请改用explode或preg_split。 - Dimitri

11
$parts = explode(" ", $str);

4

我觉得值得一提的是,尽管Gumbo发布的正则表达式对于大多数情况来说可能已经足够了,但它可能无法捕获所有空格的情况。例如,在下面的字符串上使用批准答案中的正则表达式:

$sentence = "Hello                       my name    is   peter string           splitter";

通过print_r为我提供了以下输出:
Array
(
    [0] => Hello
    [1] => my
    [2] => name
    [3] => is
    [4] => peter
    [5] => string
    [6] =>      splitter
)

当使用以下正则表达式时:

preg_split('/\s+/', $sentence);

提供了以下(期望的)输出结果:
Array
(
    [0] => Hello
    [1] => my
    [2] => name
    [3] => is
    [4] => peter
    [5] => string
    [6] => splitter
)

希望这可以帮助那些停滞在相似障碍上并感到困惑的人。

4
print_r(str_word_count("this is a sentence", 1));

结果为:

Array ( [0] => this [1] => is [2] => a [3] => sentence )

1
只是一个问题,你是想将数据转换成json格式吗?如果是的话,你可以考虑像这样做:
return json_encode(explode(' ', $inputString));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接