Page 1 of 1

Writing a forum - Parsing links

Posted: Wed Nov 22, 2006 5:32 pm
by alfone
NOTE: Square brackets [,] have been replaced with curly brackets {,} so that the forum does not parse my post.

I'm writing a barbones forum in PHP, and am having trouble figuring out how to parse the links from the user generated {url=http://www.domain.com}domain.com{/url} to the proper HTML of < a href="http://www.domain.com/" >domain.com< /a >.

The other stuff, {b}{i}{u} is easy, 'cause you can just run str_replace to switch out the user entered tags, to the html... but with the link, the domain is a wildcard and i need to grab it from between the "{url=" and the "}".

Does anybody know how to chnage {url=http://www.domain.com}domain.com{/url} to < a href="http://www.domain.com" >domain.com< /a > with a simple string function?

Thanks in advance for the help.

Posted: Wed Nov 22, 2006 5:35 pm
by Burrito
you can't do it with a 'simple string function'. You're going to need a regular expression to accommodate for variable information.

maybe something like:

Code: Select all

$pattern = "/\[url=\"(.*?)\"\](.*?)\[\/url\]/";

Posted: Wed Nov 22, 2006 5:53 pm
by feyd
You'll need XSS protection code in there too, otherwise you'll have some real fun with hackers.

Posted: Wed Nov 22, 2006 9:26 pm
by coolenta
{url=http://www.domain.com}domain.com{/url}
Im not shure if this is what you want but this is how i would do it

Code: Select all

$input = str_replace ('{url=', '<a href="', $input );
$input = str_replace ('}', '">', $input );
$input = str_replace ('{/url}', '</a>', $input );

Posted: Thu Nov 23, 2006 5:25 am
by JayBird
coolenta wrote:{url=http://www.domain.com}domain.com{/url}
Im not shure if this is what you want but this is how i would do it

Code: Select all

$input = str_replace ('{url=', '<a href="', $input );
$input = str_replace ('}', '">', $input );
$input = str_replace ('{/url}', '</a>', $input );
That's a great example of how really not to do it

Posted: Thu Nov 23, 2006 8:01 am
by Ambush Commander
What you'll want to do is preg_replace_callback. The URI gets passed to the callback, who ampersand-escapes and makes sure that the scheme is sane (and not say javascript:), and then returns the final linkified URI.

Posted: Thu Nov 23, 2006 10:46 am
by John Cartwright
preg_quote() might also be of interest