dousi4257 2013-12-27 07:33
浏览 55
已采纳

使用正则表达式捕获时如何忽略单词?

I have this string:

$text = "What's your #name ?"

And I have this code capturing 'name' and '039':

preg_replace("/\B#(\w+)/", "<a href='url'>#$1</a>", $text);

Any idea about how to capture 'name' but not '039'?

  • 写回答

2条回答 默认 最新

  • douban5644 2013-12-27 07:47
    关注

    Use a negative lookbehind:

    echo preg_replace("/(?<!\S)#(\w+)/", "<a href='url'>#$1</a>", $text);
    

    Regex autopsy:

    • (?<!\S) - A negative lookbehind - to assert that the # is not preceded by a non-whitespace character
    • # - matches the # character literally
    • (\w+) - first capturing group

    Regex101 demo.

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

报告相同问题?

悬赏问题

  • ¥15 关于哈夫曼树应用得到一些问题
  • ¥15 使用sql server语句实现下面两个实验(需要代码和运行结果截图)
  • ¥20 用web解决,要给我一个完整的网页,符合上述的要求
  • ¥20 求个sql server代码和结果的图 两道题
  • ¥15 银河麒麟操作系统无法使用U盘
  • ¥100 寻找:光电二极管电路设计服务
  • ¥15 YOLOv5改进后的结构图
  • ¥15 全志v3s怎么设置高速时钟,使用的荔枝派zero开发板,串口2需要921600的波特率
  • ¥15 关于#单片机#的问题:Lora通讯模块hc-14电路图求内部原理图
  • ¥50 esp32 wroom 32e 芯片解锁