Dan*_*ugg 12 php regex backreference preg-replace
很简单; 我似乎找不到任何关于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);
Run Code Online (Sandbox Code Playgroud)
这是一个简单的例子,但我想知道这种语法(?P=name)
是否完全不受支持.语法问题,还是不存在的功能?
Dim*_*try 13
他们存在:
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);
Run Code Online (Sandbox Code Playgroud)
甚至更快
$newandimproved = preg_replace('#^user/([^/]+)$#Di', '/user/profile/$1', $string);
Run Code Online (Sandbox Code Playgroud)
preg_replace
不支持命名反向引用.
preg_replace_callback
支持命名的反向引用,但在PHP 5.3之后,所以期望它在PHP 5.2及更低版本上失败.
归档时间: |
|
查看次数: |
6837 次 |
最近记录: |