php - 仅在某些行上替换 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
- 第二行保持不变。我目前有代码可以找到其中包含 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);}
解决方案
这是一个快速的方法 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
推荐阅读
- javascript - 奇怪的过度滚动行为
- python - 了解事件过滤器以及它们在 PyQt 中的工作方式
- css - 在 Rails 中添加 link_to 后,我似乎无法在 CSS 中定位 navbar-brand 元素
- r - 在ggplot中对齐长图例标题
- python-3.x - PostgreSQL 无法将 JpegImageFile 转义为二进制,psycopg2
- docker - 在 Docker 映像中找不到 phantomjs 二进制文件,但它在那里?
- node.js - 上传带有请求和表单数据的多部分表单
- javascript - 防止 Promise.all 拒绝第一个错误的规范方法是什么?
- java - Java如何过滤包含多个嵌套列表级别的JPA对象列表
- garbage-collection - CG太早开始收集垃圾