Prevent replacements of emoticons in HTML-tags

一个人想着一个人 提交于 2019-12-11 02:54:45

问题


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 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 &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.




回答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 (&quot;dolor&quot;) 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 (&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);


来源:https://stackoverflow.com/questions/15944495/prevent-replacements-of-emoticons-in-html-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!