在PHP中完全替换字符串

时间:2010-10-29 04:39:46

标签: 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('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/'

请帮助!!!!

3 个答案:

答案 0 :(得分:2)

您可以将preg_replacem修饰符一起使用:

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

Code In Action

答案 1 :(得分:0)

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

答案 2 :(得分:0)

要么$string=str_replace("'http://www.example.com/'", "'http://www.example2.com'", $string);,因为在您的示例中,每行左右都有单引号或使用preg_replace,如下所示:

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

...如果那些单引号不应该在那里。正则表达式末尾的$表示行的结尾,^表示行的开头。期间和/需要逃脱,因此\。和\ /

我还没有测试过这段代码。这是preg_replace()http://php.net/manual/en/function.preg-replace.php

的链接
相关问题