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

3

我目前在普通字符串上使用 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.' > ';
}

1
为什么不直接按 \s*,\s* 进行分割呢? - anubhava
你能发个例子吗?我对这个函数不是很擅长。 - Jayden
3个回答

3
在这种情况下,您不需要正则表达式。使用explode会更快。
$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,该怎么办? - Jayden

2
您可以使用explodearray_map组合使用,如下所示:
$str = 'abc, hh, hey there, 1 2 3, hey_there_';
var_dump(array_map('trim',explode(',',$str)));

Fiddle


1
@Uchiha 我太懒了,没把它加到答案里 +1 - splash58
@splash58 我也有同样的想法。 - Narendrasingh Sisodia

0
你可以使用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,该怎么办? - Jayden
我更新一个答案。你将在循环中用逗号分隔,然后去除空格。 - Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接