Adam Adam - 5 months ago 10
PHP Question

Replace Markdown-like links with HTML links in a string

I have a strings of the form

"Look at this [website]{http://www.stackoverflow.com}
or at this [page]{http://www.google.com}"


and I want to parse them with PHP to

"Look at this <a href='http://wwwstackoverflow.com'>website</a>
or at this <a href='http://www.google.com'>page</a>"


How can I do this?

I though about using
str_replace()
but I dont know how to get the string between the brackets
[]
.

Answer

try it with preg_replace

$str="Look at this [website]{http://www.stackoverflow.com} or at this [page]{http://www.google.com}";

echo preg_replace('/\[(.*?)\]\{(.*?)\}/', "<a href='$2'>$1</a>", $str);

output:

Look at this <a href='http://www.stackoverflow.com'>website</a> or at this <a href='http://www.google.com'>page</a>

working Example: https://3v4l.org/jLbff

Comments