0
votes

OK. So I am building a function that will parse a bbcoded string to html. The structure of the BBCode link is like so:

[url=http://somelink.com/]Link[/url]

And I want to make it:

<a href="http://somelink.com/">Link</a>

But I also want to check if the link is valid, to protect myself from XSS. I found this regex to check for valid link:

/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/

And now, I tried to preg_match_all the $str and foreach match to check if it's url is valid and then to parse it to html, but it seems that I can't do it. Any suggestions?

2
How did you try it ? What output/error do you get ? - Radu Murzea
You may find that one of the markdowns available around the web will pull all this out for you. Github has a list of some. github.github.com/github-flavored-markdown - Toby Allen
SoboLAN here is the piece of code: $links = array(); if(preg_match('/[url=(.*)](.*)[\/url]/', $str, $links)) { echo '<pre>' . print_r($links, true) . '</pre>'; } It doesn't match what I want. - nvlbg

2 Answers

0
votes

Take a look at PHP's built-in Filter module. It's available since PHP 5.2 and contains FILTER_VALIDATE_URL constant to filter valid urls. See some usage examples.

Never used this personally, but I believe relaying on language built-in capabilities is much safer than using regexes in your case (since you don't seem regex-proficient).

0
votes

Why re-invent the wheel?

You can use the PECL extension to parse BBCode