为什么preg_match_all()多次创建相同的答案


Why does preg_match_all() create the same answer multiple times?

以下代码从tweet中提取#标签,并将它们放入变量$matches中。

$tweet = "this has a #hashtag a  #badhash-tag and a #goodhash_tag";
preg_match_all("/(#'w+)/", $tweet, $matches);
var_dump( $matches );

有人能向我解释一下为什么下面的结果有2个相同的数组,而不是只有1吗?

array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(8) "#hashtag"
    [1]=>
    string(8) "#badhash"
    [2]=>
    string(13) "#goodhash_tag"
  }
  [1]=>
  array(3) {
    [0]=>
    string(8) "#hashtag"
    [1]=>
    string(8) "#badhash"
    [2]=>
    string(13) "#goodhash_tag"
  }
}

因为您使用()来捕获子组。

尝试:

preg_match_all("/#'w+/", $tweet, $matches);

为什么要使用(),除非你想让它做到这一点。lol对不起,结果不那么友好:(

http://php.net/manual/en/function.preg-match-all.php示例3

它的简单:

从表达式中删除()

希望能有所帮助。