【问题标题】:preg_split not splitting on spacepreg_split 不分割空间
【发布时间】:2015-03-10 12:48:26
【问题描述】:

我正在尝试使用preg_split 在任意数量的空格上拆分字符串,在用空格替换字母或数字以外的任何内容之后...这是我的代码(包括一些调试内容):

$input = strtolower($data_current[0]);
$input = preg_replace('/[^a-z0-9]/', ' ', $input);
echo($input."\r\n");
$array = preg_split('/[\s]+/', $input, PREG_SPLIT_NO_EMPTY);
print_r($array);
die;

假设$data_current[0] 的值为'hello world'。我得到的输出是这样的......

hello world
array
(
    [0] => hello world
)

显然,我期待一个包含两个值的数组...“hello”和“world”。

这里到底发生了什么?如果有帮助,则从 CSV(使用 fgetcsv)中读取 $data_current 数组...

【问题讨论】:

  • 使用 $array =explode(' ',$input) 怎么样?
  • 我想分割多个空格。

标签: php regex preg-replace preg-split


【解决方案1】:

问题是您使用的是PREG_SPLIT_NO_EMPTY,但您将它作为第三个参数而不是第四个参数,实际上是设置了一个限制,请参阅preg_split() 上的手册。

你应该使用:

preg_split('/\s+/', $input, -1, PREG_SPLIT_NO_EMPTY);
                                ^^ flags go in the 4th parameter of the function
                            ^^ default value, no limit

或:

preg_split('/\s+/', $input, NULL, PREG_SPLIT_NO_EMPTY);

【讨论】:

    【解决方案2】:

    要按两个或多个空格分隔,请更改

    $array = preg_split('/[\s]+/', $input, PREG_SPLIT_NO_EMPTY);
    

    $array = preg_split('/[\s][\s]+/', $input);
    

    【讨论】:

      猜你喜欢
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 2014-11-29
      • 1970-01-01
      • 1970-01-01
      • 2019-08-25
      • 2016-02-11
      相关资源
      最近更新 更多