Smiley Replace in CDATA HTML-String

I have a simple problem :( I need to replace text smiles with an appropriate emoticon. OK .. this is not very difficult, but now I only need to replace appereances emoticons outside of HTML tags. Short examplae:

Text:

Thats a good example :/ .. with a <a href="http://www.foobar.com">link</a> inside.

I want to replace ": /" with the image of this emoticon ...

ok, how to do it in the best way?

+3
source share
6 answers

script, .... . str ':/' . : " ( )". .

:

$smiley_array = array(
    ":) " => "<a href...>",
    " :)" => "<a href...>",
    ":/ " => "<a href...>",
    " :/" => "<a href...>");
$codes = array_keys($smiley_array);
$links = array_values($smiley_array);
$str = str_replace($codes, $links, $str);

, .

+2

, , :/- -

+1

preg_replace lookbehind. :

$smileys = array(
  ':/' => '<img src="..." alt=":/">'
);
foreach ($smileys as $smile => $img) {
  $text = preg_replace('@(?<!<[^<>]*)' . preg_quote($smile, '@') . '@',
                       $img, $text);
}

, . , .

+1

, , .

, . str_replace. "" ( ) "" .

, , - :

$smiley_array = array(":)" => "<a href...>",
    ":(" => "<a href=....>");
$codes = array_keys($smiley_array);
$links = array_values($smiley_array);
$str = str_replace($codes, $links, $str);

: , , preg_replace. , preg_replace , str_replace.

0

:

$smiley_array = array(":)" => "<a href...>",
    ":(" => "<a href=....>");
$codes = array_keys($smiley_array);
$links = array_values($smiley_array);
$str = str_replace("://", "%%QF%%", $str);
$str = str_replace($codes, $links, $str);
$str = str_replace("%%QF%%", "://", $str);

, str_replace ... :

$smiley_array = array("://" => "%%QF%%", ":)" => "<a href...>",
    ":(" => "<a href=....>", "%%QF%%" => "://");
$codes = array_keys($smiley_array);
$links = array_values($smiley_array);
$str = str_replace($codes, $links, $str);
0

( /), 99.99999999% :

<?php
$n = new DOMDocument();
$n->loadHTML('<p>Thats a good example :/ .. with a <a href="http://www.foobar.com">link</a> inside.</p>');
$x = new DOMXPath($n);
$instances = $x->query('//text()[contains(.,\':/\')]');//or use '//*[child::text()]' for all textnodes
foreach($instances as $node){
    if($node instanceof DOMText && preg_match_all('/:\//',$node->wholeText,$matches,PREG_OFFSET_CAPTURE|PREG_SET_ORDER)){
            foreach($matches[0] as $match){
                    $newnode = $node->splitText($match[1]);
                    $newnode->replaceData(0,strlen($match[0]),'');
                    $img = $n->createElement('img');
                    $img->setAttribute('src','smily.gif');
                    $img = $newnode->parentNode->insertBefore($img,$newnode);
                    //var_dump($match);
            }
    }
}
var_dump($n->saveHTML());
?>

, , , html (beit in wysiwyg , , "return" (img to text) - ( /strstr () src (, array (':/' = > 'frown.gif ')) - .

0

Source: https://habr.com/ru/post/1746838/


All Articles