php - How to return matches array and also result string using preg_replace? -
i need accomplish 2 things, , wondering if both can accomplished preg_replace.
i need alter string. right using preg_replace:
preg_replace($terms,$replace_with,$string,1);
where $terms array of terms, , $replace_with array.
but need return matches in separate array (to update other values later), because there several terms, don't know 1 has matched.
the way know how accomplish this, run preg_match first, default returns matches array, , preg_replace replace string new values.
is there way return string, , matches preg_replace only?
my end goal, have altered $string (which accomplished preg_replace), array $terms matched.
no, if $terms
, $replace_with
have numeric keys (without gaps) can use preg_replace_callback
:
$matches = []; foreach($terms $k=>$term) { $rep = $replace_with[$k]; $string = preg_replace_callback($term, function ($m) use ($rep, &$matches) { $matches[] = $m[0]; return $rep; }, $string, 1); }
note using foreach
+ preg_replace[_callback]
same thing using preg_replace
array first parameter or using preg_replace_callback_array
. (ie: string parsed once item.)
Comments
Post a Comment