1

哦,男孩,这是一个笨蛋。好吧,我在一个带有键值的数组中有一组图像。

$smiles = array( ':)' => 'http://www.example.com/happy.png', ':(' => 'http://www.example.com/sad.png' );

然后我有一个文本输入:that's sad to hear :(, but also great that you go a new dog :)

我可以解析整个数组并使用 str_replace 替换,但我希望每条消息限制为 4 个表情符号。

我的旧的(没有限制):

function addSmilies($text){
    global $smilies;

    foreach($smilies as $key => $val)
    {
        $search[] = $key;
        $replace[] = '<img src="' . $val . '" alt="' . $key . '" />';
    }

    $text = str_replace( $search, $replace, $text );
    return $text;
}

我知道您可以使用 preg_replace,这有一个限制,但我对正则表达式感到恐惧,无法让他们做我想做的事。所以回到我的问题。是否有一个带有限制的 str_replace 可以与数组一起使用,还是我应该坚持使用 preg_replace?

更新:我考虑先剥离 :) 和 :( 在我替换为实际标记之前。

function addSmilies($text){
    global $smilies;

    foreach($smilies as $key => $val)
    {
        $search[] = $key;
        $replace[] = '<img src="' . $val . '" alt="' . $key . '" />';
    }

    $limit = 4;
    $n = 1;

    for($i=0; $i<count($search); $i++)
    {
        if($n >= $limit)
            break;

        if(strpos($text, $search[$i]) === false)
            continue;

        $tis = substr_count( $text , $search[$i] ); //times in string
        $isOver = ( $n + $tis > $limit) ? true : false;
        $count = $isOver ? ($limit - $n) : $tis;

        $f = 0;
        while (($offset = strpos($text, $search[$i])) !== false)
        {
            if($f > $count)
                $text = substr_replace($text, "", $offset, strlen($search[$i]));
            $f++;
        }

        $n += $tis;
    }

    $text = str_replace( $search, $replace, $text );

    return $text;
}

但现在根本不会显示任何图像!?

4

1 回答 1

1

这是一个使用preg_split的稍微干净的函数,它包含一个限制参数(由于子集的性质,您必须添加 1)。基本上,您使用正则表达式拆分字符串,确定导致字符串拆分的模式,然后替换前四个模式,同时将字符串连接在一起。它导致更清洁的功能。

function addSmilies($text){
    $smilies = array( ':)' => 'http://www.site.com/happy.png', ':(' => 'http://www.site.com/sad.png' );

    foreach($smilies as $key => $val)
    {
        $search[] = $key;
        $replace[] = '<img src="' . $val . '" alt="' . $key . '" />';
    }

    $limit = 4; //Number of keys to replace
    $return = preg_split('/(\:\)|\:\()/',$text,$limit+1,PREG_SPLIT_DELIM_CAPTURE);

    //Concat string back together
    $newstring = "";
    foreach($return as $piece) {
        //Add more if statements if you need more keys
        if(strcmp($piece,$search[0])==0) {
            $piece = $replace[0];
        }
        if(strcmp($piece,$search[1])==0) {
            $piece = $replace[1];
        }
        $newstring = $newstring . $piece;
    }
    return $newstring;
}
于 2013-08-06T05:34:02.063 回答