0

I have a user input string with Stack Overflow style links within the string like this:

The input string [foo](http://foo.com) with a link.

and I need to transform the string to include anchor tags like this:

The input string <a href="http://foo.com">foo</a> with a link.

So far, I've got (referenced from: PHP: Best way to extract text within parenthesis?):

$text = 'ignore everything except this (text)';
preg_match('#\((.*?)\)#', $text, $match);
print $match[1];

But I need to find a way to match both the element within parentheses and the element within brackets. And finally, replace the entire matched section with a the correctly formatted anchor tag.

Does anyone know the correct regex syntax to match [foo](http://foo.com) and further how to extract "foo" and "http://foo.com"?

2
  • Look for an existing MarkDown parser. They're usually using regex for this very case too. Commented Aug 20, 2014 at 0:24
  • Thank you for the suggestion on the markdown parser. There seems to be a really good one here: parsedown.org for my purposes it might be a bit too powerful. Commented Aug 20, 2014 at 0:40

1 Answer 1

2

The below regex would match the string which is in [blah](http://blah.blah) format. The characters inside the first [] braces are captured into the group 1 and the charcters inside the next () braces are captured into group 2. Later the charcetrs inside group 1 and 2 are referenced through back-referencing (ie, recalling it with \1 or \2)

Regex:

\[([^]]*)\]\(([^)]*)\)

Replacement string:

<a href="\2">\1</a>

DEMO

PHP code would be,

<?php
$mystring = "The input string [foo](http://foo.com) with a link";
echo preg_replace('~\[([^]]*)\]\(([^)]*)\)~', '<a href="\2">\1</a>', $mystring);
?> 

Output:

The input string <a href="http://foo.com">foo</a> with a link
Sign up to request clarification or add additional context in comments.

2 Comments

Look, that's a well-written regex, as always. But just providing code-dump answers is not very helpful. In particular when OP struggles with the syntax a little explanation would be appropriate. The DEMO link does not substitute that.
That's exactly what I've been trying to create. Thank you so much for this. I'll be accepting this answer in a minute.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.