PHP 字符串替换只适用于某些行

问题描述 投票:0回答:1

我目前有一个这样的文件,我希望查找所有包含 "Hello "的行,也就是第1行和第3行。

[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
  • 在第二行没有被触动的情况下。我目前有代码可以找到所有带Hello的行,但不知道如何只编辑这几行,不编辑其他。

比如下面的代码确实找到了所有的行,但是在这个过程中也删除了所有带有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);}
php string replace
1个回答
1
投票

这里有一个快速的方法,如果 $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

1
投票

要改变任何东西,你将不得不写一个新的文件,其中包括现有的行和新改变的行。下面是一个简单的例子

// create a new output file
$out = fopen('test2.txt', 'w');

$input = file("lines.html");
$find = "Hello";
foreach($input as $key => $line){
    $tmp = $line;
    if(stristr($line, $find)){
        $tmp = str_replace('[Line', '[Changed', $line);
        // or if `[Line` can appear more than once in the line
        //$tmp = substr_replace($line, '[Changed', 0, 5);
    }
    fwrite($out, $tmp);
}
fclose($out);

结果

[Changed 1] Hello
[Line 2] World
[Changed 3] Hello World
© www.soinside.com 2019 - 2024. All rights reserved.