[英]preg_replace in php not
I'm trying to develop a batch find-and-replace for a large text file using preg_replace. 我正在尝试使用preg_replace为大型文本文件开发批处理查找和替换。 I haven't done this before, but I think I basically understand the process.
我以前没有做过,但是我想我基本上了解这个过程。 I'm having no trouble doing a straight replacement of x for y.
我毫不费力地将x替换为y。 (Numbers 0 and 2 in the arrays below are working fine.) But I can't figure out how to do an insertion that keeps the matched text.
(下面的数组中的数字0和2正常工作。)但是我不知道如何进行插入来保留匹配的文本。 I know this should be simple, and I've tried to imitate a bunch of examples.
我知道这应该很简单,并且我试图模仿很多例子。
When I run the code below, the sentence turns into "The Rabbit street mentrance of nighttown." 当我运行下面的代码时,该句子变成“夜城的兔子街头风”。 But I'm trying to turn 'Mabbot' into 'MabbotRabbit'.
但是我正在尝试将“ Mabbot”变成“ MabbotRabbit”。 How can I keep the 'Mabbot' in place?
如何将“ Mabbot”保持在原位?
Thank you! 谢谢!
<?php
$content = "The Mabbot street entrance of nighttown";
$patterns = array();
$patterns[0] = '/\n/';
$patterns[1] = '/Mabbot/';
$patterns[2] = '/entrance/';
$replacements = array();
$replacements[0] = '<br/>';
$replacements[1] = '$1Rabbit';
$replacements[2] = 'mentrance';
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $content);
?>
Change 更改
replacements[1] = '$1Rabbit';
to 至
replacements[1] = '$0Rabbit';
$1
, $2
, and so on get replaced with the match for the Nth capture group, while $0
is replaced with the whole match. $1
, $2
等等被第N个捕获组的匹配替换,而$0
被整个匹配替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.