2019-03-05 09:54
浏览 58


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: 

would become:


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


to become:


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:


The result is:


So the negative lookbehind finds [mail]e, but the rest of the email address 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?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试查找用户发布到我的在线论坛的文本中的电子邮件地址,并将其更改为公告板代码 (BB代码)。 例如: 

将成为: \ n

  [mail] [/ mail] 

但我不想更改已在的电子邮件地址 BB代码。 例如,我不想要:

  [mail] [/ mail] 


  [mail] [mail] [/ mail] [/ mail] 
   \  n 



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

我遇到的问题是负面的后视仅适用于寻找子模式的电子邮件地址的第一个字符。 例如,当应用于文本时:

  [mail] [/ mail] 


  [mail] e [mail] [/ mail] [/ mail] 
   \  n 

因此负面的lookbehind找到[mail] e,但电子邮件地址xample@yahoo.com的其余部分仍然有效。 我认为这是因为编写电子邮件地址寻求子模式的方式,因为它允许@之前的任意数量的字符。


  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题