如何用 str_replace() 替换一个词,只有当它不是另一个词的一部分时?
How to replace a term with str_replace(), only if it is not part of another word?
我有一个如下所示的文本文件:
yyy.txt:
line1
line2
line3line4
line5line3
line3
现在我想在下面的代码中将 line3
替换为 555
。但我只想在 line3
不是另一个词的一部分时替换该行,例如XYline3
或 line3XY
.
我试图用这段代码完成这个:
$filename="yyy.txt";
$line="line3";
file_put_contents($filename, str_replace($line , "555", file_get_contents($filename)));
输出:
line1
line2
555line4
line5555
555
正如你在这里看到的,它也替换了 line3line4
和 line5line3
,尽管我不想要这个。
那么我该如何更改我当前的代码,让它只替换不属于另一个词的搜索词?我有点卡在这里,不确定 str_replace()
是否可行,或者我是否必须以其他方式进行。
使用preg_replace:
$line="/\bline3\b/";
file_put_contents($filename, preg_replace($line , "555", file_get_contents($filename)));
这将替换句子中的所有单词,匹配 line3
。
要完全匹配,请使用:/^line3$/m
file_put_contents($filename, preg_replace(
"/^line3\s*$/gm" ,
"555",
file_get_contents($filename)
));
在正则表达式中,^
匹配一行的开头,line3
匹配第 3 行,\s*
匹配零个或多个 spaces/tabs,并且 $
匹配行尾。开关 gm
表示处理所有匹配项并将字符串视为多行。
带有 m
modifier 的 ^line3$
之类的正则表达式只能找到 line3
行。 m
使 ^$
匹配每一行。
https://regex101.com/r/xT7bS3/1
PHP 用法:
<?php
$string = 'line1
line2
line3line4
line5line3
line3';
echo preg_replace('/^line3$/m', '555', $string);
PHP 演示:https://eval.in/494548
首先,你的数据应该更干净,你的问题应该更有条理,无论如何,
- 打开您的文本文件,并确保在
在每一行的末尾,您将通过单击 enter 来完成此操作
每行的结尾。
使用以下脚本:
$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));
我有一个如下所示的文本文件:
yyy.txt:
line1
line2
line3line4
line5line3
line3
现在我想在下面的代码中将 line3
替换为 555
。但我只想在 line3
不是另一个词的一部分时替换该行,例如XYline3
或 line3XY
.
我试图用这段代码完成这个:
$filename="yyy.txt";
$line="line3";
file_put_contents($filename, str_replace($line , "555", file_get_contents($filename)));
输出:
line1 line2 555line4 line5555 555
正如你在这里看到的,它也替换了 line3line4
和 line5line3
,尽管我不想要这个。
那么我该如何更改我当前的代码,让它只替换不属于另一个词的搜索词?我有点卡在这里,不确定 str_replace()
是否可行,或者我是否必须以其他方式进行。
使用preg_replace:
$line="/\bline3\b/";
file_put_contents($filename, preg_replace($line , "555", file_get_contents($filename)));
这将替换句子中的所有单词,匹配 line3
。
要完全匹配,请使用:/^line3$/m
file_put_contents($filename, preg_replace(
"/^line3\s*$/gm" ,
"555",
file_get_contents($filename)
));
在正则表达式中,^
匹配一行的开头,line3
匹配第 3 行,\s*
匹配零个或多个 spaces/tabs,并且 $
匹配行尾。开关 gm
表示处理所有匹配项并将字符串视为多行。
带有 m
modifier 的 ^line3$
之类的正则表达式只能找到 line3
行。 m
使 ^$
匹配每一行。
https://regex101.com/r/xT7bS3/1
PHP 用法:
<?php
$string = 'line1
line2
line3line4
line5line3
line3';
echo preg_replace('/^line3$/m', '555', $string);
PHP 演示:https://eval.in/494548
首先,你的数据应该更干净,你的问题应该更有条理,无论如何,
- 打开您的文本文件,并确保在 在每一行的末尾,您将通过单击 enter 来完成此操作 每行的结尾。
使用以下脚本:
$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));