0

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?

1
  • Sounds like a simple string replace should work - no need for regex Commented Aug 28, 2013 at 15:17

3 Answers 3

6

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 ...

Sign up to request clarification or add additional context in comments.

6 Comments

How about if I want to do the equivalent of: $string= strtr($string, "<img src=\"$smileys\">"); second parameter has to be an array so would I just have to change every array value or is there another way to do array value and some html?
Just change the array. $smileys = Array(':)' => '<img src="smile.gif">', ':D' => '<img src="happy.gif">');
@BenFortune Okay I thought that's what would need doing, only issue is there's 70+ array items so it adds quite a bit of repetitive html.
@cars10 That g shouldn't be in there. ;)
pcre_replace too. :)
|
2

Try this:

foreach($smileys as $key => $value)
{
  str_replace($key,$value,$string);
}

Comments

0

This should do

foreach($smileys as $key=>$value){
    $string = str_replace($smiley[$key], $smiley[$value], $string);
}

1 Comment

What do you propose if his array was containing 50 smileys ? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.