简体   繁体   中英

Prevent replacements of emoticons in HTML-tags

I use a simple str_replace -function to replace some emoticons on my website…

<?php

$replace = array(
    ':)' => 'smile',
    ';)' => 'wink',
    …
);

$string = 'Lorem ipsum (&quot;dolor&quot;) sit amet! :)';

foreach($replace as $search => $replace) {
    $string = str_replace($search, '<img src="/img/'.$replace.'.png" alt="'.$search.'">', $string);
}

?>

The problem about this simple replacement is, that ";)" from the &quot; -tag would be replaced aswell and the HTML-code would be broken. Is there any way/workaround (a special regex ie) to solve this "problem"? Thanks! :)

Easiest way would be to do this:

$replace = array(
    ' :)' => ' smile',
    ' ;)' => ' wink',
);

Basically only replace the emoticons if they are preceded with a space. If a user writes:

Hello my name is John:) - that is their mistake, not yours.


A second option would be to use htmlspecialchars_decode() before replacing the emoticons.

Use preg_replace with \\B (non-word boundary)

$string = preg_replace("/\B".preg_quote($search)."\B/", '<img src="/img/'.$replace.'.png" alt="'.$search.'">', $string);

Tested

[root@srv ~]# php test.php
Lorem ipsum (&quot;dolor&quot;) sit amet! <img src="/img/smile.png" alt=":)">

use:

$string = html_entity_decode($string);

before the replacement (the foreach), this way the &quot; would be read as actual quotes, and not being replaced. And you can use htmlentities() afterward to have the &quot;'s again if you are storing on database or something.

Here is My second answer, you are right, in the end we would need to use regex. Basically There's the $negation regex prepended to the escaped searches, I guess it can be optimized but for now it worked for me.

$smileys = array(
    ':)' => 'smile',
    ';)' => 'wink'
);

$string = 'Lorem ipsum (&quot;dolor&quot;) sit amet! :)';

$negation = '[^&\w*]'; // Here is the magic, this is the part that avoids the search to be preceded by &+characters
foreach($smileys as $icon => $name) {
  $replace[] = '<img src="/img/'.$name.'.png" alt="'.$icon.'">'; //we create an array with the corresponding replaces
  $search[] = '/'.$negation.preg_quote($icon).'/'; //Magic second part, preg_quote escapes the smileys to sarch for PCRE, we prepend the magical regex.
}

$string = preg_replace($search, $replace, $string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM