user3437098 user3437098 - 23 days ago 5
PHP Question

Replace string between two brackets and get a variable on the repleaced string

This is my input string: (Picture will variate)

[image]http://picture.com/1.jpg[/image]


This is what i want to output:

<img src="http://picture.com/1.jpg">


How can i use preg_replace or other alternatives to do this?

Answer

Just for sake of completeness, here's the preg_replace solution...

$patterns = array("/\[image\]/", "/\[\/image\]/");
$replacements = array("<img src=\"", "\">");

$string = "[image]http://picture.com/1.jpg[/image]";

echo preg_replace($patterns, $replacements, $string);

Live Demo