Replace urls with hyperlinks

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Todd_Z
Forum Regular
Posts: 708
Joined: Thu Nov 25, 2004 9:53 pm
Location: U Michigan

Replace urls with hyperlinks

Post by Todd_Z »

Not the best, but an honest effort:

Code: Select all

function addLinks ( $str ) {
  $str = preg_replace( "#(http://(?:www\.)?[^\s\.]*\.[^\s$]+)#i" , "<a href=\"$1\" style=\"font-weight: bold;\">$1</a>", $str );
  echo preg_replace( "#([^/]www\.[\S$]*)#i" , "<a href=\"http://$1\" style=\"font-weight: bold;\">$1</a>", $str );
}
Critiques?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Yeah it certainly will work for most common URL's :D

I really want to write another one that actually checks for valid characters (and allows subdomains too) but I'm off to bed cos I'm tired.

In other words... yes it works.. good job ;) It will fail on subdomains and allows invalid characters too... fix that and it's brill.

URL patterns in the strictest sense can get hideously complex so only evaluate it as much as you need to (find the RFC's and have another go if you were feeling geeky enough and you'll see how complex it *can* be).

Good work ;)
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

User avatar
Todd_Z
Forum Regular
Posts: 708
Joined: Thu Nov 25, 2004 9:53 pm
Location: U Michigan

Post by Todd_Z »

Haha, i have way to much work to complete to wade through those links - but thanks timvw!
Post Reply