PHP replace text with image

2019-08-30 05:25发布

This would be an Array of data:

$array = array("sad","bow","blabla");

IF $input = "I love Stackoverflow! :bow: so much";

Output should be:

I love Stackoverflow <img src="smiley/bow.gif" alt=""/> so much

What would be the best and fastest way to accomplish this ?

2条回答
一夜七次
2楼-- · 2019-08-30 06:07
$array = array(':('=>"sad",'-_-'=>"bow",'bla'=>"blabla");
$input = "I love Stackoverflow! :bow: so much";
$output = str_replace(array_keys($array), array_values($array), $input);

Edit: Sorry..didn't read it clearly.

Attempt 2:

preg_replace('`:(\w+):`', '<img src="smily/\1.gif" alt=""/>', $input);

Someting like that anyway.

Might have to use $1 in place of \1. Read the docs.

查看更多
相关推荐>>
3楼-- · 2019-08-30 06:07
//string replace example.
$input = "I love Stackoverflow! :bow: so much"; 
echo str_replace(":bow:","< img src='smiley/bow.gif' alt=''/>",$input)."<br /><br />";


//use string replace with foreach 
$array = array("sad","bow","blabla");

foreach($array as $value)
{
  $input = "I love Stackoverflow! :'".$value."': so much";
  echo str_replace(":'".$value."':","< img src='smiley/$value.gif' alt=''/>",$input);  
}
查看更多
登录 后发表回答