用PHP的preg_replace替换文本中的部分内容

3
我正在尝试找到一种替换这样的文本的方法:

text here ABC -some text here- CED text here

to

text here ABC -replaced text- CED text here

或者-----------------------------------
text here ABC - some description here- CED text here

to

text here ABC - replaced text- CED text here

这句话的意思是,我们将开始一个文本部分,以“ABC”开头并以“CED”结尾,用“替换文本”替换它们之间的所有文本。您该如何做到这一点呢?谢谢。

像这样吗?preg_replace('/ABC(.*?)CED/', 'ABC - new - CED', $string); - Mihai Iorga
2个回答

6
要替换ABCCED之间的内容,您可以使用正向回顾后发断言正向先行断言来保留ABCCED并将其替换为所需内容。如果文本之间还包括换行符,则可以使用s修饰符来强制点.匹配换行符。
$str = 'text here ABC -some text here- 
CED text here';

$str = preg_replace('/(?<=ABC).*?(?=CED)/si', ' foo ', $str);
echo $str;

请查看演示版

正则表达式:

(?<=           look behind to see if there is:
 ABC           'ABC'
)              end of look-behind
 .*?           any character except \n (0 or more times)
 (?=           look ahead to see if there is:
  CED          'CED'
 )             end of look-ahead

2
<?php
$myText = 'text here ABC -some text here- CED text here';
$myText = preg_replace('/ABC(.+)CED/', 'ABC - replaced text - CED', $myText);
echo $myText;

CodePad


非常感谢,它对我有效。我可以再问你一个问题吗? 如果我的文本像这样 “文本在此ABC -一些文本在此- CED文本在此” 这意味着在CED之前有一个换行符,我该如何处理? - tungcan
s标志添加到模式的末尾。 新模式应为/ABC(.+)CED/s([示例](http://codepad.org/1bazBxTR)),这将告诉preg_replace,`.`代表所有字符,包括换行符`\n`。 - casraf
请记住,在这里您可能想要添加 ? 以进行非贪婪匹配。 - hwnd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接