加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 使用preg_replace命名反向引用

发布时间:2020-12-13 16:01:01 所属栏目:PHP教程 来源:网络整理
导读:很简单我似乎没有找到关于 PHP的preg_replace()支持命名反向引用的任何定义: // should match,replace,and output: user/profile/foo$string = 'user/foo';echo preg_replace('#^user/(?Pid[^/]+)$#Di','user/profile/(?P=id)',$string); 这是一个微不足道
很简单我似乎没有找到关于 PHP的preg_replace()支持命名反向引用的任何定义:
// should match,replace,and output: user/profile/foo
$string = 'user/foo';
echo preg_replace('#^user/(?P<id>[^/]+)$#Di','user/profile/(?P=id)',$string);

这是一个微不足道的例子,但我想知道是否不支持这种语法(?P = name).语法问题或不存在的功能?

它们存在:

http://www.php.net/manual/en/regexp.reference.back-references.php

使用preg_replace_callback:

function my_replace($matches) {
    return '/user/profile/' . $matches['id'];
}
$newandimproved = preg_replace_callback('#^user/(?P<id>[^/]+)$#Di','my_replace',$string);

甚至更快

$newandimproved = preg_replace('#^user/([^/]+)$#Di','/user/profile/$1',$string);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读