Is there any way I can replace one value and retrieve another in the same string in a more efficient way than in the code below, for example a method that combines preg_replace()
and preg_match()
?
$string = 'abc123';
$variable = '123';
$newString = preg_replace("/(abc)($variable)/",'$1$2xyz', $string);
preg_match("/(abc)($variable)/", $string, $matches);
$number = $matches[2];
You can use a single call to
preg_replace_callback()
and update the value of$number
in the code of the callback function:I don't think there is a big speed improvement. The only advantage could be on the readability.