dongmu2174 2017-08-15 07:58 采纳率: 100%
浏览 88
已采纳

正则表达式查找自定义符号附带的单词或句子

I need to replace some words or some sentences and convert it to underline. I'm using PHP and find one reference: PHP Regex, extract all custom tags from text

Somehow, the case only covers for single words but not sentences. How to make the regex also can catch everything enclosed by ## tag?

Let say my input will be such as:

"ll the Lorem Ipsum ##generators## on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over ##200 Latin words##, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always ##free from repetition##, injected humour, or non-characteristic words etc."

Then the output will be:

"ll the Lorem Ipsum ____1____ on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over ____2____, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always ____3____, injected humour, or non-characteristic words etc."

Can anyone help me on how to get the regex pattern?

  • 写回答

2条回答 默认 最新

  • dqq9695 2017-08-15 08:03
    关注

    I think the regex is:

    /##[^#]+##/g
    

    [Regex Demo]


    $text = 'll the Lorem Ipsum ##generators## on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over ##200 Latin words##, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always ##free from repetition##, injected humour, or non-characteristic words etc.';
    
    preg_match_all('/##[^#]+##/', $text, $matches, PREG_SET_ORDER);
    
    for ($i = 0; $i < count($matches); $i++) {
      $text = preg_replace("/".$matches[$i][0]."/", "___".strval($i+1)."___" , $text, 1);
    }
    

    [PHP Demo]

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看