preg_match()
stores the matches into an array which you supply as the third parameter. In this case your preg_match()
statement looks like:
preg_match('/(?<= )@([^@ ]+)/', $string, $matches);
So $matches
contain all the matches, where:
$matches[0]
will contain the text that matched the full pattern$matches[1]
will have the text matched by the first capturing group$matches[2]
will have the text matched by the second capturing group- and so on...
The regular expression here is (?<= )@([^@ ]+)
. It matches @120rb ORDER BB
completely, so it will be stored in $matches[0]
, whereas the capturing group ([^@ ]+)
will only capture the part after the @
(120rb ORDER BB
) and it will be stored in $matches[1]
.
Currently, the regular expression doesn't detect if a mention is at the beginning of the string. Also, it'd incorrectly match whitespace on the next line as [^@]
will match anything that's not a @
symbol. I'd use the following expression with preg_match_all()
:
(?<=^|\s)@([^@\s]+)
Code:
if (preg_match_all('/(?<=^|\s)@([^@\s]+)/', $string, $matches)) {
print_r($matches[1]);
}
To get the number of matches, you can just use echo count($matches[0]);
.