停留在带有反向引用的简单 preg_replace

stuck on a simple preg_replace with backreference

对不起各位,我卡住了:

$data_update = preg_replace($id.'(.*?)'.$s.PHP_EOL, $id..$s.$text.PHP_EOL, $data_update, 1);

$id = '23423';
$s = '|';
$text = 'content to insert';

基本上我想要做的是匹配包含多行的平面文件文本中 $id 和 PHP 行尾之间的所有内容,并将其替换为插入了一些内容的同一行就在行尾之前。我在末尾有“1”修饰符,因为我希望这只发生在与该 id 匹配的行上。

我做错了什么?

我建议使用

preg_replace('/\b(' . $id . '\b.*)(\R)/', ' ' . $text . '', $data_update, 1);

模式看起来像 \b(23423\b.*)(\R) 并且匹配

  • \b - 单词边界
  • (23423\b.*) - 第 1 组:ID 作为一个完整的词,然后是行的其余部分
  • (\R) - 第 2 组:任何换行序列

full PHP demo:

$id = '23423';
$s = '|';
$text = 'content to insert';
$data_update = "Some text 23423 in between end\nsome text";
$data_update = preg_replace('/\b(' . $id . '\b.*)(\R)/', ' ' . $text . '', $data_update, 1);

输出:

Some text 23423 in between end content to insert
some text