php中的精确字符串替换

php中的精确字符串替换,php,string,replace,Php,String,Replace,我正在寻找一种方法来替换php中与主题完全匹配的字符串 例如,我得到一个名为“hello world.txt”的文件,其中有三行: 'http://www.example.com/' 'http://www.example.com/category/' 'http://www.example.com/tag/name/' 我需要更换'http://www.example.com/“带”http://www.example2.com“ $string=file_get_contents('hel

我正在寻找一种方法来替换php中与主题完全匹配的字符串

例如,我得到一个名为“hello world.txt”的文件,其中有三行:

'http://www.example.com/'
'http://www.example.com/category/'
'http://www.example.com/tag/name/'
我需要更换
'http://www.example.com/“
”http://www.example2.com“

$string=file_get_contents('hello-world.txt');
$string=str_replace('http://www.example.com/','http://www.example2.com',$string);
echo $string;
我将得到与此类似的结果:

'http://www.example2.com/'
'http://www.example2.com/category/'
'http://www.example2.com/tag/name/'
但我真正需要的是这样的东西:

'http://www.example2.com/'
'http://www.example.com/category/'
'http://www.example.com/tag/name/'
$string=preg_replace('/^http:\/\/www\.example\.com\/$/', 'http://www.example2.com/', $string);

请帮忙

首先检查当前行是否是您要查找的行。如果没有,就把它吐出来。

或者
$string=str\u replace(“'http://www.example.com/'", "'http://www.example2.com“,$string)因为在您的示例中,每行都有单引号,或者使用preg_replace,如下所示:

'http://www.example2.com/'
'http://www.example.com/category/'
'http://www.example.com/tag/name/'
$string=preg_replace('/^http:\/\/www\.example\.com\/$/', 'http://www.example2.com/', $string);
。。。如果那些单引号不应该存在的话。正则表达式末尾的$表示行的结尾,^表示行的开头。期间和/或需要转义,因此\。及\/


我还没有测试过这段代码。这里有一个指向preg_replace()的链接您可以将
preg_replace
m
修饰符一起使用,如下所示:

$string=preg_replace('~^http://www\.example\.com/$~m','http://www.example2.com',$string);

字符串是如何分离的?我已经测试了您发布的代码,它似乎工作正常。我发现的唯一问题是你在str_replace的第二个参数中漏掉了一个/,这将使它输出:嗯。。。文本似乎已被编辑过一些。请澄清一下,OP是只需要替换当前所说的第一个值,还是只替换第一个值,他需要替换所有值,正如我最初记得的那样?嗨,从codaddict$string=preg_replace(“~^\.example\.com/$~m,”)获得了解决方案;