preg_replace使用PHP开始和结束文本的一部分

 阿梓喵1995 发布于 2023-02-09 14:05

我正试图找到一种方法来替换这样的文本:

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"结尾的文本的一部分,用"替换文本"替换它们之间的所有文本.我怎样才能做到这一点?谢谢.

1 个回答
  • 要替换它们之间的内容ABC,CED您可以使用Positive LookbehindPositive Lookahead来保留ABCCED,并将其替换为您想要的内容.如果两者之间的文本也包含换行符,则可以使用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
    

    2023-02-09 14:07 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有