2015-12-29 26 views
-1

我有一个文本文件,如下所示:如何用str_replace()替换一个词,仅当它不是另一个词的一部分?

yyy.txt:

line1      
line2      
line3line4  
line5line3  
line3 

现在我想在下面的代码555更换line3。但是,如果line3不是另一个单词的一部分,我只想替换该行,例如XYline3line3XY

我试着用这个代码来实现:

$filename="yyy.txt"; 
$line="line3"; 

file_put_contents($filename, str_replace($line , "555", file_get_contents($filename))); 

输出:

line1 

line2 

555line4 

line5555 

555 

正如你可以在这里看到它也换成line3line4line5line3即使我不想这样。

那么,如何更改我目前的代码,它只会替换搜索词,如果它不是另一个词的一部分?我有点卡在这里,不知道这是可能的str_replace()或如果我必须以另一种方式做到这一点。

+1

你需要使用正则表达式或更具体的'search'字符串。 – chris85

+0

你的问题的格式非常分散。请格式化并澄清您的具体问题。 – chris85

+0

请勿多次发布相同或接近相同的问题。 –

回答

4

使用preg_replace

$line="/\bline3\b/";  
file_put_contents($filename, preg_replace($line , "555", file_get_contents($filename))); 

这将替换所有单词在句子中,匹​​配line3

正好相匹配,使用方法:/^line3$/m

+0

\ b是字边界......所以如果一行有“foo line3 bar”,上面的正则表达式会导致“foo 555 bar” – BareNakedCoder

+0

@BareNakedCoder更新! – Thamilan

+1

错字错误!已修复 – Thamilan

0
file_put_contents($filename, preg_replace(
    "/^line3\s*$/gm" , 
    "555", 
    file_get_contents($filename) 
)); 

在正规快件,^比赛开始线,line3比赛,好了,3号线,\s*匹配零个或多个空格/制表符和$比赛队伍的尽头。开关gm表示处理所有匹配并将字符串视为多行。

+0

PHP中没有'g'修饰符。 'preg_replace'默认是全局的。 – chris85

0

首先,你的数据应该是更清洁,你的问题应该更有组织,不管怎么说,

  1. 打开你的文本文件,并确保t处有一个RC字符他在每行的结尾,你会通过点击输入在每行的末尾 完成。
  2. 使用下面的脚本:

    $filename="yyy.txt"; 
    $content = file_get_contents($filename); 
    $content = preg_replace ('/(\r)+line3(\r)+/', "\r555\r" , $content); 
    $content = preg_replace ('/(\n)+line3(\n)+/', "\n555\n" , $content); 
    file_put_contents($filename, preg_replace ('/(\s)+line3(\s)+/', "\s555\s" , $content)); 
    
+0

为什么要有3个正则表达式? '\ s'会发现'\ n'和'\ r'也没有理由对它们进行分组,我没有看到在替换字符串中使用'\ r'的原因,可能是'\ n'。 – chris85

+0

确保正确的行为,无论是隐藏的字符。请注意,传递的数据不干净,行之间的字符将是任何东西! –

+0

'\ s'是任何空格字符......'\ s代表“空白字符”。再一次,这实际包含哪些字符取决于正则表达式的风格。在本教程讨论的所有风格中,它都包含[\ t \ r \ n \ f]。即:\ s匹配空格,制表符,换行符或换页符.'- http://www.regular-expressions.info/shorthand.html也不需要分组。 – chris85

相关问题