将字符串中的表情符号替换为关键字
大多数表情符号替换功能的结构如下:
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。这样做有什么好处呢?
Most emoticon replacement functions are stuctured as follows:
array(
':-)' => 'happy', ':)' => 'happy', ':D' => 'happy', ...
)
This, to me, seemed a bit redundant (especially while I don't need to make a distinction between 'happy', such as :-) and VERY happy, such as :-D. So I've come up with this:
$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;
}
The output should be:
RT @MW_AAPL: Apple officially rich HAPPY LOLWUT #ipod SAD
However, I don't know how to call the correct key from $emoticons. In my code, it seems to always replace any emoticon with keyword "HAPPY".
(1) If you see what's wrong with my code, then please let me know. Any help would be greatly appreciated :-)
(2) I'm using str_replace here, while I see many other funciotns use preg_replace. What would be the advantage of that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该足够了,利用
str_replace
接受数组作为其前两个参数中的任何一个:查看实际操作。
This should be enough, taking advantage of the fact that
str_replace
accepts arrays for any of its first two parameters:See it in action.
将此:更改
为:
Change this:
to this: