0

I'm looking for the way to replace emoticons in php and my code is below.

function emotify($text)
{
    $icons = array(
        '3:)'   =>  '<li class="emoti emoti55"></li>',
        'O:)'   =>  '<li class="emoti emoti54"></li>',
        ':)'   =>  '<li class="emoti emoti00"></li>',
        '>:('   =>  '<li class="emoti emoti19"></li>',
        ':('   =>  '<li class="emoti emoti01"></li>',
        ':P'   =>  '<li class="emoti emoti14"></li>',
        '=D'   =>  '<li class="emoti emoti08"></li>',
        '>:o'   =>  '<li class="emoti emoti18"></li>',
        ':o'   =>  '<li class="emoti emoti15"></li>',
        ';)'   =>  '<li class="emoti emoti04"></li>',
        ':/'   =>  '<li class="emoti emoti03"></li>',
        ':\'('   =>  '<li class="emoti emoti05"></li>',
        '^_^'   =>  '<li class="emoti emoti18"></li>',
        'B|'   =>  '<li class="emoti emoti09"></li>',
        '<3'   =>  '<li class="emoti emoti65"></li>',
        '-_-'   =>  '<li class="emoti emoti40"></li>',
        'o.O'   =>  '<li class="emoti emoti10"></li>',
        '(y)'   =>  '<li class="emoti emoti81"></li>',
        );
    return str_replace(array_keys($icons), array_values($icons), $text);
}

//test work well
echo emotify(":) :( :P =D :o ;) :v >:( :/ :'( ^_^ 8-) B| <3 3:) O:) -_- o.O >:o :3 (y) ");

I want if there is string concatenate with left or right sides of emoticon codes , don't replace it. For example:

http://www.google.com   aaa:)bbb   :)111111   22222:)

I think this may done by using preg replace(?) Please help, Many thanks.

Marcus
  • 295
  • 4
  • 16

1 Answers1

0

If you want to preserve the speed advantage of strtr (that is the fastest way to translate literal strings (the string is parsed only once for all key/values)), you can proceed in three passes.

The first pass consists to replace what you want to protect with a placeholder. Example:

$protected = array('http://'  => '#!#0#!#',
                   'https://' => '#!#1#!#',
                   'ftp://'   => '#!#2#!#', // etc.
);
$str = strtr($str, $protected);

Note that the build of $protected can be easily automated from array('http://', 'https://', 'ftp://', ...);

Second pass, you use your array:

$str = strtr($str, $icons);

Third pass, you replace the placeholders:

$str = strtr($str, array_flip($protected));

Even if you need three passes to do it, the result will be from far faster than using preg_replace that will parse the string once for each key/value.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • not only the link but this too `aaa:/aaa`, `:/aaa` or `aaa:/` don't want to replace – Marcus Dec 05 '14 at 20:00
  • @Marcus: the idea is to store these particular cases in `$protected`. These cases are obviously limited, so it isn't difficult to identify them and to define a placeholder for each of them. – Casimir et Hippolyte Dec 05 '14 at 20:03