douhui1630 2016-03-17 00:34
浏览 29
已采纳

如何匹配字符串中特定范围之间的特定字符?

I have this string:

$str = "here is start of rage, also here is some text and here is the end of string";
//              ^^^^^                                                 ^^^
//                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Now I'm trying to remove all e letter between this range: [start - end]. Well I want this output:

$newstr = "here is start of rag, also hr is som txt and hr is th end of string";

How can I do that?

  • 写回答

4条回答 默认 最新

  • dougou2937 2016-03-17 01:56
    关注

    With preg_replace and the \G anchor:

    echo preg_replace('~(?:\G(?!\A)|\bstart\b)[^e]*\K(?:\Be|e(?!nd\b))~S', '', $str);
    

    details:

    ~
    (?:
        \G(?!\A)   # contiguous to the previous match, not at the start of the string
      |            # OR
        \bstart\b  # the word "start"
    )
    [^e]*          # all that is not an "e"
    \K             # exclude all previous matched characters from the whole match 
    (?:
        \Be        # an "e" that is not the start of a word
      |            # OR
        e(?!nd\b)  # an "e" that is not followed by "nd"
    )
    ~  
    S  # the STUDY modifier that tries to improve non-anchored patterns
    

    This pattern find one "e" at a time. Once the word "start" is found, the \G anchor forces the next match to be contiguous, since it matches the position at the end of the previous match. When the word "end" is reached (?:\Be|e(?!nd\b)) fails and the contiguity is broken (until an other eventual word "start").

    Note that this pattern doesn't check if the word "end" exists in the string (but it can easily be done). If the word "end" doesn't exist, all "e" will be removed from the word "start" until the end of the string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵