【问题标题】:How can I convert a sentence to an array of words?如何将句子转换为单词数组?
【发布时间】:2025-11-22 07:30:01
【问题描述】:

从这个字符串:

$input = "Some terms with spaces between";

我怎样才能产生这个数组?

$output = ['Some', 'terms', 'with', 'spaces', 'between'];

【问题讨论】:

    标签: php arrays string split


    【解决方案1】:

    您可以使用explodesplitpreg_split

    explode 使用固定字符串:

    $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));
    

    【讨论】:

    • php 5.3 中不推荐使用 split 函数,因此请改用 explode 或 preg_split
    【解决方案2】:
    $parts = explode(" ", $str);
    

    【讨论】:

      【解决方案3】:
      print_r(str_word_count("this is a sentence", 1));
      

      结果:

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

      【讨论】:

        【解决方案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
        )
        

        希望它可以帮助任何陷入类似障碍并且对原因感到困惑的人。

        【讨论】:

          【解决方案5】:

          只是一个问题,但是您是否要从数据中生成 json?如果是这样,那么您可能会考虑这样的事情:

          return json_encode(explode(' ', $inputString));
          

          【讨论】: