我在一个相当大的文件上使用file_get_contents
。在其中,我需要找到以下各项的每个实例:
http://www.example.com/?foo=1&bar=3
并将其更改为:
http://www.example.com?foo=1&bar=4
我的问题是不明白preg_replace
将如何仅替换正则表达式上的部分匹配项,而不是整个字符串。例如,伪代码如下所示:
$content = file_get_contents($filename);
$pattern = '/http:'/'/www'.example'.com/'?foo=1'&bar=('d+)';
preg_replace($pattern, "4", $content);
file_put_contents($filename, $content);
我几乎可以肯定preg_replace($pattern, "4", $content);
在这种情况下是错误的。在这里用"4"替换"3"的正确方法是什么?
使用'K
:重置报告的匹配项的起点。任何以前消耗的角色都不再包含在最终匹配中
$pattern = '/http:'/'/www'.example'.com'/'?foo=1'&bar='K'd+/';
preg_replace($pattern, "4", $content);
演示
您还可以使用回溯:
$pattern = '/(?<=http:'/'/www'.example'.com'/'?foo=1'&bar=)'d+/';
preg_replace($pattern, "4", $content);
演示
$content = file_get_contents($filename);
$pattern = '/http:'/'/www'.example'.com'/'?foo=1'&bar=('d+)/i';
$content = preg_replace($pattern, "http://www.example.com/?foo=1&bar=4", $content);
file_put_contents($filename, $content);