2011-10-26 60 views
0

大多数表情替换功能stuctured如更换表情如下:字符串中使用关键字

array(
    ':-)' => 'happy', ':)' => 'happy', ':D' => 'happy', ... 
) 

这对我来说,似乎有点多余(尤其是当我不需要做出区分“高兴” ,如:-)和非常高兴,如: - D.所以我想出了这一点:

$tweet = 'RT @MW_AAPL: Apple officially rich :-) LOLWUT #ipod :('; 

function emoticons($tweet) { 
    $emoticons = array(
    'HAPPY' => array(':-)', ':-D', ':D', '(-:', '(:'), 
    'SAD' => array(':-(', ':('), 
    'WINK' => array(';-)', ';)'), 
    ); 

    foreach ($emoticons as $emotion) { 
    foreach ($emotion as $pattern) { 
     $tweet = str_replace($pattern, key($emoticons), $tweet); 
    } 
    } 

    return $tweet; 
} 

输出应该是:

RT @MW_AAPL: Apple officially rich HAPPY LOLWUT #ipod SAD 

不过,我不知道如何从$调用正确的密钥表情。在我的代码中,它似乎总是用关键字“HAPPY”替换任何表情符号。 (1)如果你看到我的代码出了什么问题,请让我知道。任何帮助将不胜感激:-) (2)我在这里使用str_replace,而我看到许多其他funciotns使用preg_replace。那会有什么好处呢?

回答

2

这应该是足够的,采取的是str_replace接受数组用于任何前两个参数的事实优势:

foreach ($emoticons as $emot => $icons) { 
    $tweet = str_replace($icons, $emot, $tweet); 
} 

See it in action

1

更改此:

foreach ($emoticons as $emotion) { 
    foreach ($emotion as $pattern) { 
     $tweet = str_replace($pattern, key($emoticons), $tweet); 
    } 
} 

这样:

foreach ($emoticons as $key => $emotion) { 
     $tweet = str_replace($emotion, $key, $tweet); 
}