【问题标题】:split string by any amount of whitespace in PHP在 PHP 中用任意数量的空格分割字符串
【发布时间】:2013-06-22 20:11:06
【问题描述】:

我知道如何使用 .explode() by " " 将分隔符之间的单词拆分为数组中的元素。

但这只会将字符串拆分为一个空格字符。如何按任意数量的空格进行拆分?

因此,数组中的一个元素在找到空格时结束,而数组中的下一个元素在找到第一个下一个非空格字符时开始。

所以像"The quick brown fox" 这样的东西变成了一个数组,返回数组中的元素是 The、quick、brown 和 fox。

"jumped over the lazy dog" 也会拆分,因此每个单词都是返回数组中的一个单独元素。

【问题讨论】:

    标签: php arrays string


    【解决方案1】:

    像这样:

    preg_split('#\s+#', $string, null, PREG_SPLIT_NO_EMPTY);
    

    【讨论】:

      【解决方案2】:
      $yourSplitArray=preg_split('/[\ \n\,]+/', $your_string);
      

      【讨论】:

        【解决方案3】:

        试试这个

         preg_split(" +", "hypertext language    programming"); //for one or more whitespaces
        

        【讨论】:

          【解决方案4】:

          你可以在这里看到:PHP explode() Function

          <?php
              $str = "Hello world. It's a beautiful day.";
              print_r (explode(" ",$str));
          ?>
          

          将返回:

          Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-09-22
            • 1970-01-01
            • 1970-01-01
            • 2014-12-13
            相关资源
            最近更新 更多