PHP 中的表情符号替换有一些条件


Emoticons replacement in PHP with some conditions

我正在寻找在 php 中替换表情符号的方法,我的代码如下。

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

我想要如果有字符串与表情符号代码的左侧或右侧连接,请不要替换它。例如:

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

我认为这可以通过使用preg replace(?请帮忙,非常感谢。

如果你想保持strtr的速度优势(这是翻译文字字符串的最快方法(字符串只对所有键/值解析一次)),你可以分三次继续。

第一遍包括用占位符替换要保护的内容。例:

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

请注意,$protected的构建可以很容易地从array('http://', 'https://', 'ftp://', ...);自动化

第二遍,您使用数组:

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

第三遍,替换占位符:

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

即使你需要三次传递才能做到这一点,结果也会比使用preg_replace快得多,因为将为每个键/值解析一次字符串。