如果匹配字符串不在数组中,则跳过preg_replace

时间:2016-03-07 11:32:29

标签: php preg-replace

我有函数替换字符串ex。 :smile:带有图片标签。

function out_emoj($str)
{

    $emoj_array = array(
        "cry", "grimacing", "joy","smiley","innocent", "wink", "flushed", "slight_smile",
        "stuck_out_tongue_winking_eye", "relaxed", "crab","cat","expressionless", "pig", "rose", "cherry_blossom",
        "sunny", "cloud_snow", "coffee","tea","grin", "ring", "crown", "nerd",
        "heart_eyes", "kissing_heart", "sunglasses","scream","rage","disappointed","fearful","confused",
        "dizzy_face", "zipper_mouth", "thermometer_face","sleeping","ghost","smiley_cat","smile_cat","joy_cat",
        "heart_eyes_cat", "smirk_cat", "kissing_cat","scream_cat","crying_cat_face","pouting_cat","thumbsup","thumbsdown",
        "angel", "dancer", "kimono","heart","purple_heart","sparkling_heart","heart_decoration","snowflake",
        );

    return preg_replace("/:(.*?):/", " <img width='22' src='".base_url('assets/img/emojiones/$1.png')."' alt='$1'> ", $str);

}

我想检查匹配字符串是否在数组中,然后替换else skip。 例如:如果用户输入:notfound:function将添加带有不存在的图像的标签。我想检查一下&#34; notfound&#34;先排在阵列中。

2 个答案:

答案 0 :(得分:1)

Prince Actarus,您可以将preg_replace_callback添加到您的golgot武器中:

return preg_replace_callback("/:(.*?):/", function ($m) use ($emoj_array) {
    if (in_array($m[1], $emoj_array))
        return ' <img width="22" src="' . base_url('assets/img/emojiones/' . $m[1] . '.png') . '" alt="' . $m[1] . '"> ';
    return $m[0];
}, $str);

另一种方法是构建一个映射原始数组的模式数组并使用preg_replace,但效率较低,因为每个模式都会解析一次字符串。

其他方式:建立替代方案:

$pattern = '/:(' . implode('|', $emoj_array) . '):/';

return preg_replace($pattern, ' <img width="22" src="' . base_url('assets/img/emojiones') . '/$1.png" alt="$1"> ', $str);

答案 1 :(得分:0)

function out_emoj($str)
{
    $emoj_array = array(
        "cry", "grimacing", "joy","smiley","innocent", "wink", "flushed", "slight_smile",
        "stuck_out_tongue_winking_eye", "relaxed", "crab","cat","expressionless", "pig", "rose", "cherry_blossom",
        "sunny", "cloud_snow", "coffee","tea","grin", "ring", "crown", "nerd",
        "heart_eyes", "kissing_heart", "sunglasses","scream","rage","disappointed","fearful","confused",
        "dizzy_face", "zipper_mouth", "thermometer_face","sleeping","ghost","smiley_cat","smile_cat","joy_cat",
        "heart_eyes_cat", "smirk_cat", "kissing_cat","scream_cat","crying_cat_face","pouting_cat","thumbsup","thumbsdown",
        "angel", "dancer", "kimono","heart","purple_heart","sparkling_heart","heart_decoration","snowflake",
        );

    return preg_replace_callback("/:(.*?):/",
        function($m) use ($emoj_array)
        {

            if (in_array($m[1],$emoj_array))
            {
                return " <img width='22' src='".base_url('assets/img/emojiones/'.$m[1].'.png')."' alt='{$m[1]}'> ";
            }
            else
            {
                return ':'.$m[1].':';
            }
        } 
     , $str);

}

谢谢@Casimir et Hippolyte和@ rizier123这里是我的解决方案