2010-10-29 54 views
0

我正在寻找一种方法来替换一个字符串在PHP中完全匹配的主题。在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/' 

请帮助!!!!

+0

如何琴弦分开吗? – Jason 2010-10-29 04:46:36

+0

我测试了你发布的代码,它似乎工作正常。我发现的唯一问题是在str_replace的第二个参数中省略了/,这将使其输出:http://www.example2.com http://www.example2.comcategory/ http:// www .example2.comtag/name/ – OmnipotentEntity 2010-10-29 04:50:35

+0

嗯......似乎文本已被编辑了一些。请澄清一下,OP是否只需要替换现有的第一个值,还是只替换第一个值,而且他们需要将它们全部替换掉​​,正如我原来记得它说的那样? – OmnipotentEntity 2010-10-29 05:34:21

回答

2

您可以使用preg_replacem修改为:

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

Code In Action

+0

非常感谢您的解决方案。 – sreejith 2010-10-29 05:49:20

+0

非常感谢你:) – yanike 2012-03-29 03:49:55

0

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

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