【问题标题】:Replace emoticons in string with keywords用关键字替换字符串中的表情符号
【发布时间】:2011-12-15 19:13:45
【问题描述】:

大部分表情替换功能的结构如下:

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

但是,我不知道如何从 $emoticons 中调用正确的键。在我的代码中,它似乎总是用关键字“HAPPY”替换任何表情符号。

(1) 如果您发现我的代码有什么问题,请告诉我。任何帮助将不胜感激 :-) (2) 我在这里使用 str_replace,而我看到许多其他功能使用 preg_replace。这样做有什么好处?

【问题讨论】:

    标签: php preg-replace str-replace


    【解决方案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);
    }
    

    【讨论】:

      【解决方案2】:

      这应该足够了,利用 str_replace 的前两个参数中的任何一个接受数组这一事实:

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

      See it in action.

      【讨论】:

        猜你喜欢
        • 2020-03-14
        • 1970-01-01
        • 1970-01-01
        • 2016-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-19
        • 1970-01-01
        相关资源
        最近更新 更多