我正试图找到一种方法来替换这样的文本:
text here ABC -some text here- CED text here
至
text here ABC -replaced text- CED text here
要么 - - - - - - - - - - - - - - - - - -
text here ABC - some description here- CED text here
至
text here ABC - replaced text- CED text here
这意味着,我们将开始以"ABC"开头并以"CED"结尾的文本的一部分,用"替换文本"替换它们之间的所有文本.我怎样才能做到这一点?谢谢.
要替换它们之间的内容ABC
,CED
您可以使用Positive Lookbehind和Positive Lookahead来保留ABC和CED,并将其替换为您想要的内容.如果两者之间的文本也包含换行符,则可以使用s
修饰符强制点.
也匹配换行符.
$str = 'text here ABC -some text here- CED text here'; $str = preg_replace('/(?<=ABC).*?(?=CED)/si', ' foo ', $str); echo $str;
看到 Working demo
正则表达式:
(?<= 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