Reputation: 12096
I have a string of text:
$string = "This is a comment :) :D";
and an array of keys with values:
$smileys = Array(':)' => 'smile.gif', ':D' => 'happy.gif');
I want to replace any occurrences of array keys in the string with their related value so the output string would be:
$string = "This is a comment smile.gif happy.gif";
How can I do this? I've tried looping as below but no luck?
foreach($smileys as $smiley){
$string = preg_replace("~\b$smileys\b~", $smileys[$smiley], $string);
}
Edit
I also wish to add some html between the array and replace so:
:D
turns into
<img src="/happy.gif" />
but would the same html need to be in every array value if strtr
were used?
Upvotes: 0
Views: 1389
Reputation: 28196
try
$string= strtr($string,$smileys);
This will walk through $string
and replace each occurence of each key in $smileys
with the associated value.
Edit:
To include the <img>
tags into the string you could post-process the whole string with a single
$string=preg_replace('/([\w]+\.gif)/i','<img src="$1">',$string);
This of course relies on the assumption that all your gif names do not contain any blanks and that there are no other words like image.gif
in your string since they would be affected too ...
Upvotes: 6
Reputation: 26370
Try this:
foreach($smileys as $key => $value)
{
str_replace($key,$value,$string);
}
Upvotes: 2
Reputation: 1805
This should do
foreach($smileys as $key=>$value){
$string = str_replace($smiley[$key], $smiley[$value], $string);
}
Upvotes: 0