Gandalf
November 17, 2016, 4:48pm
1
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
cpradio
November 17, 2016, 4:51pm
2
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
Gandalf
November 17, 2016, 5:08pm
3
Thanks @cpradio . Dead simple suits me in more ways than one 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)
cpradio
November 17, 2016, 5:56pm
4
What you have looks right to me.
cpradio
November 17, 2016, 6:15pm
5
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
Gandalf
November 17, 2016, 6:30pm
6
Brill, thanks @cpradio . I shoulda noticed the need to escape the double quotes!
system
Closed
February 17, 2017, 1:31am
7
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.