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条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题