首页 > 解决方案 > 在文件中搜索字符串并替换该行中字符之后的所有内容

问题描述

我正在寻找使用 PHP 打开一个文件(参见下面的示例),逐行搜索字符串$colour并替换"="with之后的所有内容$value

file.txt 之前:

red=0
green=23
blue=999
yellow=44

如果我$value"1"并且我的颜色是"blue",我的文件应该更改为:

red=0
green=23
blue=1
yellow=44

到目前为止,我的代码是:

function write($colour, $value) {
    $file = 'path';
    $file_contents = file_get_contents($file);
    $file_contents = str_replace($colour, $value, $file_contents);
    file_put_contents($file, $file_contents);
}

然而,这只是$colour$value(不是“=”之后的所有内容)替换我的输出:

red=0
green=23
1=999
yellow=44

我该怎么做呢?谢谢!

标签: phpfilefile-handlingwrite

解决方案


问题是您只是将颜色的文本替换为中的值

$file_contents = str_replace($colour, $value, $file_contents);

不过,这并不能取代整行。

使用preg_replace(),您可以替换以颜色开头的内容,然后=用...替换直到行尾。

$file_contents = preg_replace("/{$colour}=.*/", "{$colour}={$value}", $file_contents);

推荐阅读