I have regex like this:
^page/(?P\\d+)-(?P[^\\.]+)\\.html$
and an array:
$args = array(
\'id\' =&
Interesting challenge, I coded something that works for this sample, note that you need PHP 5.3+ for this code to work:
$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.