【问题标题】:stuck on a simple preg_replace with backreference卡在带有反向引用的简单 preg_replace
【发布时间】:2020-05-03 21:43:11
【问题描述】:

对不起,我被困在这个问题上:

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

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

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

我做错了什么?

【问题讨论】:

  • 为什么使用$s="|"?请发布行示例。也许你需要preg_replace('/\b(' . $id . '\b.*)(\R)/', '$1 ' . $text . '$2', $data_update, 1);?见this PHP demo
  • @WiktorStribiżew 我需要为 EOL 打补丁,因为行尾已作为 PHP_EOL 插入到平面文件文本中,因此您可以将我的数据变量视为:$data_update = "23423 in between some text".PHP_EOL;$data_update .= "00000 in between some more text".PHP_EOL;@987654328 @
  • 如果您需要帮助,请提供MCVE (minimal complete verifiable example)
  • 您的示例有所帮助,PHP 演示对我来说非常棒!谢谢你! @WiktorStribiżew

标签: php regex preg-replace regex-group backreference


【解决方案1】:

我建议使用

preg_replace('/\b(' . $id . '\b.*)(\R)/', '$1 ' . $text . '$2', $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)/', '$1 ' . $text . '$2', $data_update, 1);

输出:

Some text 23423 in between end content to insert
some text

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    相关资源
    最近更新 更多