preg_match_all用逗号分隔,值可能包含空格

时间:2015-07-06 06:37:10

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

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

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

但是当涉及空间时,我的当前脚本就会停止。

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

3 个答案:

答案 0 :(得分:3)

在这种情况下,你不需要定期表达。爆炸会更快

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

结果相同

答案 1 :(得分:2)

您可以将explodearray_map一起用作

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

Fiddle

答案 2 :(得分:0)

您可以使用explode():

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

foreach($array as $row){
    echo trim($row, ' ');
}
相关问题