意外的Regexp结果*

时间:2014-07-17 14:58:11

标签: php regex preg-match-all

我正在尝试设计一个提取的正则表达式:

aa
bb
cc

来自主题:

aa,bb,cc

我正在使用以下正则表达式:

|(.+?),*|

但结果是

a
a
b
b
c
c

请帮忙,

感谢。

3 个答案:

答案 0 :(得分:3)

从索引1获取匹配的组。

(\w+),?

DEMO

示例代码:

$re = "/(\\w+),?/m";
$str = "aa,bb,cc";

preg_match_all($re, $str, $matches);

您也可以使用PHP: Split string使用explode

$myArray = explode(',', $myString);

了解更多How can I split a comma delimited string into an array in PHP?

答案 1 :(得分:2)

?使您的匹配非贪婪',这意味着它将匹配满足正则表达式的最短字符串。此外,,*表示0 or more commas

您正在寻找的是:

|[^,]+|

例如:

<?php
$foo = "aa,bb,cc";
preg_match_all("/[^,]+/",$foo,$matches);
for($j=0;$j<count($matches[0]); $j++){
  print $matches[0][$j] .  "\n";
}
?>

答案 2 :(得分:1)

没有任何团体,

(?<=^|,)\w+

OR

\w+(?=,|$)

DEMO

PHP代码将是,

<?php
$data = "aa,bb,cc";
$regex =  '~(?<=^|,)\w+~';
preg_match_all($regex, $data, $matches);
var_dump($matches);
?>

输出:

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(2) "aa"
    [1]=>
    string(2) "bb"
    [2]=>
    string(2) "cc"
  }
}
相关问题