Home » Php » php – Is it possible to replace each capturing group in a regex with a different string

php – Is it possible to replace each capturing group in a regex with a different string

Posted by: admin February 25, 2020 Leave a comment

Questions:

If I have a regex like this: (\.\d+)|([A-Z]\d{2}\.-)

Can I replace capturing group $1 with string a and capturing group $2 with string b within one regex replace?

preg_replace($pattern, $replace, $value);

.123A12.- to Value-aValue-b or .123funA12 to Value-afunValue-b

How to&Answers:

This is how I solved it:

<?php
$patterns = array ('/\.\d+/','/[A-Z]\d{2}\.-/');
$replace = array ('Value-a','Value-b');
echo preg_replace($patterns, $replace, '.123funA12.-');
?>

See here and here for information.

Answer:

Of course, just use $1, $2 and so on:

preg_replace($pattern, "$1_something_else$2", $value);

E.g. .123A12.- (which would match your expression) would then be replaced to

.123_something_elseA12.-