php - 在文件中搜索字符串并替换该行中字符之后的所有内容
问题描述
我正在寻找使用 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
我该怎么做呢?谢谢!
解决方案
问题是您只是将颜色的文本替换为中的值
$file_contents = str_replace($colour, $value, $file_contents);
不过,这并不能取代整行。
使用preg_replace()
,您可以替换以颜色开头的内容,然后=
用...替换直到行尾。
$file_contents = preg_replace("/{$colour}=.*/", "{$colour}={$value}", $file_contents);
推荐阅读
- pandas - 计算熊猫速度的平均值
- c - 为什么我的 bison/flex 没有按预期工作?
- weka - 在 weka 的 KNN 中解释分类器输出参数,如 -K、-W、-A
- rust - 使用 Result 在控制流中产生副作用的推荐方法是什么?
- php - 为什么我们需要特定的类来处理请求和响应?
- android - Google Places Autocomplete - 如何访问原始用户输入
- python - 如何在数据框中的每一列中输入一些值
- symfony - 如何在 Doctrine 中为 Cast(X $comparisonOperator Y) 编写/扩展自定义 DQL 函数?(目标:显示相关对象)
- javascript - 我可以在 this.state 路径中使用函数参数作为通配符吗?前任。this.state.{参数}.value
- wordpress - 在特定的 WordPress 页面上禁用页面查询变量