Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The following code extracts #hashtags from a tweet and puts them in the variable $matches.

$tweet = "this has a #hashtag a  #badhash-tag and a #goodhash_tag";

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

var_dump( $matches );

Can someone please explain to me why the following results have 2 identical arrays instead of just 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"
  }
}
like image 992
Joncom Avatar asked Feb 17 '26 01:02

Joncom


1 Answers

Because you use () to catch the sub group.

Try:

preg_match_all("/#\w+/", $tweet, $matches);
like image 95
xdazz Avatar answered Feb 18 '26 14:02

xdazz