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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mortz
Forum Newbie
Posts: 10
Joined: Wed May 19, 2004 4:23 am
Location: Norway

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

Post 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:
leenoble_uk
Forum Contributor
Posts: 108
Joined: Fri May 03, 2002 10:33 am
Location: Cheshire
Contact:

Post by leenoble_uk »

$newText = preg_replace("/\bhttp:\/\/([_\.0-9a-z\/-]+)\b/i","<a href=\"http://\\1\" target=\"_blank\">\\1</a> ", $oldText);
mortz
Forum Newbie
Posts: 10
Joined: Wed May 19, 2004 4:23 am
Location: Norway

Post by mortz »

Wow! That was a quick reply! Thanks!
leenoble_uk
Forum Contributor
Posts: 108
Joined: Fri May 03, 2002 10:33 am
Location: Cheshire
Contact:

Post 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.
mortz
Forum Newbie
Posts: 10
Joined: Wed May 19, 2004 4:23 am
Location: Norway

Post by mortz »

Cool.
Post Reply