Help with regex

Regexes tend to fry my brain! I’m looking for a regex to translate a Markdown link into an HTML anchor tag. eg.

[I'm an inline-style link](http://www.domain.com)

into

<a href="http://www.domain.com">I'm an inline-style link</a>

Can anyone help please? Thanks

How particular do you want to be regarding the link? Do you care if it is properly formatted?

/\[(.*)\]\((.*)\)/g is the dead simple way, it will give you two groups, one that matches what is in the [] and one that matches what is in the ()

1 Like

Thanks @cpradio. Dead simple suits me in more ways than one :smiley: I guess I need something along the lines of this to effect the translation, but which bits do I need to quote and which bits to escape???

$html = preg_replace("/\[(.*)\]\((.*)\)/g", "<a href="$2">$1</a>", $markdown) 

What you have looks right to me.

Here is what I threw together, and it seems to work.

<?php
$markdown = "[I'm an inline-style link](http://www.domain.com)";
$html = preg_replace("/\[(.*)\]\((.*)\)/", "<a href=\"$2\">$1</a>", $markdown);
var_dump($html);
1 Like

Brill, thanks @cpradio. I shoulda noticed the need to escape the double quotes!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.