Page 1 of 1

regexp question: Get URLs from a string and convert to Links

Posted: Wed May 19, 2004 4:23 am
by mortz
Hi!

Hm. Let us say that we have a string like the one belov.

Code: Select all

<?php
$string = "blablabla... http://site.com/dir/page.php?var=something blablabla... http://anothersite.com/ blablabla";
?>
How to find the URL's and convert them to links like belov?

Code: Select all

<?php
$string = "blablabla... <a href="http://site.com/dir/page.php?var=something" target="_blank">http://site.com/dir/page.php?var=something</a> blablabla... <a href="http://anothersite.com/" target="\blank">http://anothersite.com/</a> blablabla";
?>
Hope you did understand my question :wink:

I'm not so steady with regular expressions :oops:

Posted: Wed May 19, 2004 4:38 am
by leenoble_uk
$newText = preg_replace("/\bhttp:\/\/([_\.0-9a-z\/-]+)\b/i","<a href=\"http://\\1\" target=\"_blank\">\\1</a> ", $oldText);

Posted: Wed May 19, 2004 4:48 am
by mortz
Wow! That was a quick reply! Thanks!

Posted: Wed May 19, 2004 4:51 am
by leenoble_uk
I copied and pasted it from a site I'd already written it for.
Here's one for email addresses too:

Code: Select all

$new = preg_replace("/\b([_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6})\b/", "<a href="mailto://\\1">\\1</a>", $old);
and yes, I used the Quick Reply box.

Posted: Wed May 19, 2004 8:01 am
by mortz
Cool.