问题
I use a simple str_replace
-function to replace some emoticons on my website…
<?php
$replace = array(
':)' => 'smile',
';)' => 'wink',
…
);
$string = 'Lorem ipsum ("dolor") 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 "
-tag would be replaced aswell and the HTML-code would be broken. Is there any way/workaround (a special regex i.e.) to solve this "problem"? Thanks! :)
回答1:
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.
回答2:
use:
$string = html_entity_decode($string);
before the replacement (the foreach), this way the "
would be read as actual quotes, and not being replaced. And you can use htmlentities() afterward to have the "'s
again if you are storing on database or something.
回答3:
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 ("dolor") sit amet! <img src="/img/smile.png" alt=":)">
回答4:
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 ("dolor") 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);
来源:https://stackoverflow.com/questions/15944495/prevent-replacements-of-emoticons-in-html-tags