Simple use preg_match
before preg_replace
, eg
preg_match($regex, $str, $matches);
Assuming the pattern actually matched, you should have the results in $matches[0]
and $matches[1]
which are the equivalent of $0
and $1
in the replace string.
FYI, the $n
tokens in the replacement string are not variables though I can see how that can be confusing. They are simply references to matched groups (or the entire match in the case of $0
) in the regex.
See http://php.net/manual/function.preg-replace.php#refsect1-function.preg-replace-parameters
To find multiple matches in $str
, use preg_match_all()
. It's almost the same only it populates $matches
with a collection of matches. Use the PREG_SET_ORDER
flag as the 4th argument to make the array workable. For example...
$str = ' xD #lol and #testing';
$regex = '/#(\w+)/';
preg_match_all($regex, $str, $allMatches, PREG_SET_ORDER);
print_r($allMatches);
produces...
Array
(
[0] => Array
(
[0] => #lol
[1] => lol
)
[1] => Array
(
[0] => #testing
[1] => testing
)
)