简体   繁体   中英

Replace array keys with values inside a string

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?

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

Try this:

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

This should do

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM