防止替换HTML标签中的表情符号 [英] Prevent replacements of emoticons in HTML-tags

查看:145
本文介绍了防止替换HTML标签中的表情符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用简单的str_replace功能替换了我网站上的某些表情符号...

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);
}

?>

关于这种简单替换的问题是,&quot;-标记中的;)"也将被替换,并且HTML代码将被破坏.有什么方法/解决方法(即特殊的正则表达式)解决此问题"吗?谢谢! :)

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 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 (&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);

这篇关于防止替换HTML标签中的表情符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆