【问题标题】:preg_match_all separated by commas with values probably containing spacespreg_match_all 用逗号分隔,值可能包含空格
【发布时间】:2015-09-23 04:52:30
【问题描述】:

我目前有一个 preg_match_all 用于不包含空格的常规字符串,但我现在需要使其适用于每个空格之间的任何内容。

我需要abc, hh, hey there, 1 2 3, hey_there_ 才能返回 abchhhey there``1 2 3hey_there_

但我当前的脚本会在涉及空格时停止。

preg_match_all("/([a-zA-Z0-9_-]+)+[,]/",$threadpolloptions,$polloptions);
foreach(array_unique($polloptions[1]) as $option) {
     $test .= $option.' > ';
}

【问题讨论】:

  • 为什么不直接用\s*,\s*分割
  • 你能发布例子吗?不太擅长这个功能。

标签: php regex preg-match preg-match-all


【解决方案1】:

在这种情况下,您不需要正则表达式。爆炸会更快

$str = 'abc, hh, hey there, 1 2 3, hey_there_';
print_r(explode(', ', $str));

结果

Array
(
    [0] => abc
    [1] => hh
    [2] => hey there
    [3] => 1 2 3
    [4] => hey_there_
)

更新

$str = 'abc, hh,hey there, 1 2 3, hey_there_';
print_r(preg_split("/,\s*/", $str));

结果一样

【讨论】:

  • 如果用户这样提交怎么办one,two, three, four, five,six
【解决方案2】:

您可以将explodearray_map 一起用作

$str = 'abc, hh, hey there, 1 2 3, hey_there_';
var_dump(array_map('trim',explode(',',$str)));

Fiddle

【讨论】:

  • @Uchiha 我懒得把它添加到答案+1
  • @splash58 我也想到了同样的事情
【解决方案3】:

你可以使用explode():

$string = "abc, hh, hey there, 1 2 3, hey_there_";
$array = explode(',', $string);

foreach($array as $row){
    echo trim($row, ' ');
}

【讨论】:

  • 如果用户这样提交怎么办one,two, three, four, five,six
  • 我更新了一个答案。您将用“,”分隔,然后在循环中修剪一个空格。
猜你喜欢
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
  • 2011-08-02
  • 2021-07-23
  • 1970-01-01
  • 2012-04-28
  • 2013-07-01
  • 2015-07-08
相关资源
最近更新 更多