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?

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

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

  example@yahoo.com 
   
 
 

将成为: \ n

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

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

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

成为:

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

因此,我需要在正则表达式中添加负向lookbehind断言,以确保电子邮件地址不在字符[mail](或只是)之前。

我正在使用的PHP代码是:

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

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

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

结果是:

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

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

如何更改正则表达式,以便在寻找子模式的整个电子邮件地址中使用负面的背后应用程序,同时仍能成功捕获大部分发布的电子邮件地址?

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

2条回答 默认 最新

相关推荐 更多相似问题