Reputation: 4099
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?
Upvotes: 0
Views: 780
Reputation: 437336
This should be enough, taking advantage of the fact that str_replace
accepts arrays for any of its first two parameters:
foreach ($emoticons as $emot => $icons) {
$tweet = str_replace($icons, $emot, $tweet);
}
Upvotes: 2
Reputation: 22142
Change this:
foreach ($emoticons as $emotion) {
foreach ($emotion as $pattern) {
$tweet = str_replace($pattern, key($emoticons), $tweet);
}
}
to this:
foreach ($emoticons as $key => $emotion) {
$tweet = str_replace($emotion, $key, $tweet);
}
Upvotes: 1