反向preg_replace [英] Reverse preg_replace

查看:145
本文介绍了反向preg_replace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的正则表达式:

I have regex like this:

^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

推荐答案

有趣的挑战,我编写了一些适用于此示例的代码,请注意,要使此代码起作用,您需要PHP 5.3 +:

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;

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

在线演示 .

Online demo.

这篇关于反向preg_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆