Search code examples
phpregexstr-replaceemojimailto

regex / str_replace: issue with mailto and smiley combination


Edit: Example

When a user enters [email protected], the visible result becomes:

[email protected]" class="small">[email protected]

But if a user enters [email protected], the visible result becomes just that: [email protected], and it becomes a link. When the user clicks the link, it prompts their local e-mail program on their computer and the recipient field is auto-filled with [email protected]


The issue I'm having

I'm working on a site where users can comment on each other's pages, and I'm using str_replace and regex to replace urls into clickable urls, hashtags into "clickable hashtags", smiley codes (:P, :S, :D) into images etc.

However, when I try to turn an e-mail into a mailto with preg_replace, my "tongue"-smiley (:P) breaks it:

// MAILTO
$text = preg_replace('/(\S+@\S+\.\S+)/', '<a href="mailto:$1" class="small">$1</a>', $text);

// SMILEY
$text = str_replace(':P', '<img src="images/smileys/tongue.png" class="smiley" alt=":P" />', $text);

If a user enters an e-mail that starts with the letter "P", the mailto breaks and I'm basically screwed.

String input:

<a href='mailto:[email protected]'>[email protected]</a>

Becomes:

<a href='mailto[SMILEY][email protected]'>[email protected]</a>

One obvious solution is of course to change the smiley code (:P) into something else, or simply not create clickable e-mails. But ":P" is so widely known and used by users, so it's a matter of user experience. Also I have other smileys like the ":S" etc, so I'm hoping to find a simple, practical solution to this.

Any help will be much appreciated!


Solution

  • Try this code snippet here

    Regex: /(?<!mailto):(?:P|p)/ This expression says match :p or :P when there is no mailto word before it.

    Instead of this:

    $text = str_replace(':P', '<img src="images/smileys/tongue.png" class="smiley" alt=":P" />', $text);
    

    Use this:

    $text=  preg_replace('/(?<!mailto):(?:P|p)/', '<img src="images/smileys/tongue.png" class="smiley" alt=":P" />', $text);