PDA

View Full Version : Parsing URLs


Steviepowers
Wed 22nd May '02, 7:40am
How do I parse all URLs in some text so they become hyperlinks instead of just being text URLs

Mark Hensler
Wed 22nd May '02, 1:52pm
// HYPERLINKS \[url="http://xxx"\]yyy\[/url\]
$string = preg_replace("#\\[url=&quot;(ftp://|https://|http://|mailto:)(.*)&quot;\\](.*)\\[/url\\]#U","<a href=\"\\\\1\\\\2\" target=_blank>\\\\3</a>",$string);
// HYPERLINKS \[url="xxx"\]yyy\[/url\]
$string = preg_replace("#\\[url=&quot;(.*)&quot;\\](.*)\\[/url\\]#U","<a href=\"http://\\\\1\" target=_blank>\\\\2</a>",$string);
// HYPERLINKS \[url=http://xxx\]yyy\[/url\]
$string = preg_replace("#\\[url=(\ftp://\https://|http://|mailto:)(.*)\\](.*)\\[/url\\]#U","<a href=\"\\\\1\\\\2\" target=_blank>\\\\3</a>",$string);
// HYPERLINKS \[url=xxx\]yyy\[/url\]
$string = preg_replace("#\\[url=(.*)\\](.*)\\[/url\\]#U","<a href=\"http://\\\\1\" target=_blank>\\\\2</a>",$string);
// HYPERLINKS \[url\]http://xxx\[/url\]
$string = preg_replace("#\\[url\\](ftp://|https://|http://|mailto:)(.*)\\[/url\\]#U","<a href=\"\\\\1\\\\2\" target=_blank>\\\\2</a>",$string);
// HYPERLINKS \[url\]xxx\[/url\]
$string = preg_replace("#\\[url\\](.*)\\[/url\\]#U","<a href=\"http://\\\\1\" target=_blank>\\\\1</a>",$string);
I think this is right. I had to double escape everything so that the php tags wouldn't jack it up.

Conscience
Thu 23rd May '02, 6:08pm
mark that only deals with having [url] tags... he is asking to parse all urls in text with or without custom tags...

Of course, stevie, you can easily modify the preg_replace code mark has provided you with to do what you want :D

I would suggest looking up preg and ereg functions in the php manual because they are some of the most useful parsing tools around.

Mark Hensler
Fri 24th May '02, 12:09am
/me slaps self
Sorry, forgot.

I've answered this question before so I tried to search for those threads. I couldn't find them.

Play with the above code for a while. Let me know if you need me to go looking for that other stuff again.