dongsi7067 2019-03-05 09:54
浏览 58
已采纳

在查找电子邮件地址时,如何使PHP正则表达式断言适用于整个模式?

I am trying to find email addresses in text posted by users to my online forum, and change them into Bulletin Board Code (BBCode). So for instance:

example@yahoo.com 

would become:

[mail]exmaple@yahoo.com[/mail]  

However I don't want to change email addresses that are already in BBCode. So for instance, I don't want:

[mail]exmaple@yahoo.com[/mail]

to become:

[mail][mail]exmaple@yahoo.com[/mail][/mail]

Therefore I need to add a negative lookbehind assertion to my regular expression to ensure that an email address is not preceeded by the characters [mail] (or just ]).

The PHP code I'm using is:

$pattern = '#(?<!])([a-zA-Z0-9_\-\.]*@\S+\.\w+)#';
$bbcode = '[mail]$1[/mail]';
preg_replace($pattern, $bbcode, $text);

The problem I have is that the negative lookbehind is only applied to the first character for the email address seeking sub-pattern. For example when applied to the text:

[mail]example@yahoo.com[/mail]

The result is:

[mail]e[mail]xample@yahoo.com[/mail][/mail]

So the negative lookbehind finds [mail]e, but the rest of the email address xample@yahoo.com still validates. I reaise that this is because of the way the email address seeking sub-pattern is written, because it allows for any number of characters before the @.

How can I change the regular expression to make the negative lookbehind appliy to the whole of the email address seeking sub-pattern, whilst still successfully catching the majority of email addresses being posted?

  • 写回答

2条回答 默认 最新

  • doukuizuo1795 2019-03-05 10:04
    关注

    You need to have a word boundary at the beginning of regex to avoid matching the text partially, and also use + instead of * for the username part in email regex. Try using this regex,

    (?<!])\b([a-zA-Z0-9_\-\.]+@\S+\.\w+)(?!\[)
    

    Demo

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

报告相同问题?

悬赏问题

  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?