哦,男孩,这是一个笨蛋。好吧,我在一个带有键值的数组中有一组图像。
$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;
}
但现在根本不会显示任何图像!?