防止替换HTML标签中的表情符号 [英] Prevent replacements of emoticons in HTML-tags
问题描述
我使用简单的str_replace
功能替换了我网站上的某些表情符号...
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);
}
?>
关于这种简单替换的问题是,"
-标记中的;)"也将被替换,并且HTML代码将被破坏.有什么方法/解决方法(即特殊的正则表达式)解决此问题"吗?谢谢! :)
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! :)
推荐答案
这是我的第二个答案,您是对的,最后我们需要使用正则表达式.
基本上,转义的搜索前面有$negation
正则表达式,我想可以对其进行优化,但现在对我有用.
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);
这篇关于防止替换HTML标签中的表情符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!