反转preg_replace

时间:2013-05-11 14:22:27

标签: php regex preg-replace generator

我有这样的正则表达式:

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

和一个数组:

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

我想有功能:

my_function($regex, $args)

将返回此结果:

page/5-my-first-article.html

如何实现这一目标?

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

这样的东西

1 个答案:

答案 0 :(得分:6)

有趣的挑战,我编写了适用于此示例的内容,请注意您需要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;

输出: page/5-my-first-article.html

<强> Online demo