N
N
Nikolai Chuprik2018-06-20 01:05:49
PHP
Nikolai Chuprik, 2018-06-20 01:05:49

How to make a substitution from an array with a key from a regular expression?

There is an array:

$routes = array( [1] => 'one', [2] => 'two', [3] => 'three' );

There is a text containing numbers in constructions of the form '{a 1}', '{a 3}', etc., in which these same numbers must be replaced with words from the array. How to do it? The regular expression suggests itself, but I don’t understand how to take the found numbers as an index. I want something like this: (I will conditionally write a deliberately incorrect syntax, but you will understand):
preg_replace("/\{a (\d+)}/g", "<a href=\"".$routes[\\1]."\">", $text);

Well, how to do it normally?
Thanks for the help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-06-20
@0xD34F

$text = preg_replace_callback("/\{a (\d+)\}/", function($matches) use($routes) {
  return "{a ".$routes[$matches[1]]."}";
}, $text);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question