Hey.

I can not deal with regulars. Her task is to parse the text and replace the email addresses with mailto links:

$text = preg_replace("#(^|[\n ])([\w0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#iu", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $text); 

Everything works only when there are any characters in front of the address. For example:

test@test.com - does not work.

test test@test.com - works.

UPD: It turned out that the prefilter of the line adds <p> at the beginning. I am not very strong in regulars, so I’ll additionally ask if such a solution to the problem is normal:

 (^|>|[\n ])([\w0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+) 
  • one
    @ silent-box, you need more information. For example, what text was checked? [Your example works] [1] [1]: ideone.com/y3m5pT - VenZell
  • An example of the text on which this replacement does not work, please provide. [ideone.com] [1] [1]: ideone.com/TzzTf1 - Opalosolo
  • "#^([\n\s]*)([\w&\-_\.]+?)@([\w\-]+\.([\w\-\.]+\.)*\w+)#iu" - etki
  • Yes, in online services it really works. So the problem is in my place, not in the regular season. Thank! I will sort this out. ___ Indeed, the case turned out to be that the case was previously passed through a filter that adds <p> before the line. - silent-box

1 answer 1

Instead:

 (^|[\n ]) 

better to use:

 \b 

After the dog, you use " \ w ", which includes " _ ", which is not in the domains.
Try something simpler, like this:

 \b([\w-]+@[a-z0-9-.]+)\b 

In general, there are tons of ready-made regulars in the network.

  • Thank you, I will consider! And what do you say about the account <p> at the beginning of the line? (unsubscribed at the end of the question itself) Will it be normal to write (\ b | <p>)? - silent-box
  • Read about the value of \ b, you will understand everything. - technobulka