To handle captured values during replacement, you can use the preg_replace_callback function. It is used when it is necessary to perform any actions with captured offsets before inserting them into the modified drain.
An example of code that replaces words based on an associated array and converts domain names to uppercase:
$str = '[[Яша|ya.ru]] qwerty [[Яков|yandex.ru]]'; $dict = ['Яша' => 'Яков', 'Яков' => 'Яша']; // Словарь для замены имён $res = []; // Массив для найденных имён echo preg_replace_callback( '~\[\[(.*?)\|(.*?)]]~', function ($m) use ($dict, &$res) { // $m - объект совпадения, $m[0] - всё совпадение, $m[1] - значение первой группы и т.д. array_push($res, $m[1]); // Добавление в массив найденных имён return '<a href="'. mb_strtoupper($m[2]) . // Значение группы №2 в верхний регистр '" target="_blank">'. (isset($dict[$m[1]]) ? $dict[$m[1]] : $m[1]) . // Замена имени из словаря, если имеется '</a>'; }, $str ) . "\n"; print_r($res); // Вывод найденных имён
Result:
<a href="YA.RU" target="_blank">Яков</a> qwerty <a href="YANDEX.RU" target="_blank">Яша</a> Array ( [0] => Яша [1] => Яков )
Pay attention to use ($dict, &$res) : $dict can be used only for reading, and &$res - for reading and writing (thanks to & ).
preg_replace_callback()- teran