Reverse preg_replace

I have a regex:

^page/(?P<id>\d+)-(?P<slug>[^\.]+)\.html$ 

and array:

 $args = array( 'id' => 5, 'slug' => 'my-first-article' ); 

I would like to have a function:

 my_function($regex, $args) 

which will return this result:

 page/5-my-first-article.html 

How can this be achieved?

Something like https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse

+4
source share
1 answer

An interesting call, I encoded something that works for this example, note that for this code you need PHP 5.3+:

 $regex = '^page/(?P<id>\d+)-(?P<slug>[\.]+)\.html$'; $args = array( 'id' => 5, 'slug' => 'my-first-article' ); $result = preg_replace_callback('#\(\?P<(\w+)>[^\)]+\)#', function($m)use($args){ if(array_key_exists($m[1], $args)){ return $args[$m[1]]; } }, $regex); $result = preg_replace(array('#^\^|\$$#', '#\\\\.#'), array('', '.'), $result); // To remove ^ and $ and replace \. with . echo $result; 

Output: page/5-my-first-article.html

online demo .

+6
source

Source: https://habr.com/ru/post/1480242/


All Articles