首页 > 解决方案 > 仅在某些行上替换 PHP 字符串

问题描述

我目前有这样的文件。

[Line 1] Hello
[Line 2] World
[Line 3] Hello World

我希望查找包含“Hello”的所有行,即第 1 行和第 3 行。

然后我想在那条线上将“Line”的所有情况更改为“Changed”,因此输出将是

[Changed 1] Hello
[Line 2] World
[Changed 3] Hello World

例如,下面的代码确实找到了所有行,但也使用 str_replace 删除了进程中的所有内容,所以我知道我正在寻找的不是 str_replace。

$lines = file("lines.html");
$find = "Hello";
$repl = "Changed";
foreach($lines as $key => $line)
  if(stristr($line, $find)){$line = str_replace("$find","$repl",$line);}

标签: phpstringreplace

解决方案


这是一个快速的方法 if$find = "Hello";$repl = "Changed";

$result = preg_replace("/\[Line (\d+\].*?$find.*)/", "[$repl $1", file("lines.html"));
file_put_contents("lines.html", $result);
  • 匹配[Line并捕获一个或多个()数字\d+
  • 后面是任何东西,.*?然后是$find字符串,然后是.*捕获所有内容的任何东西
  • 替换为[ $repl和捕获的内容$1

推荐阅读