Jump to content


Photo

Reg Exp to replace hyperlinks


  • Please log in to reply
3 replies to this topic

#1 macgyver

macgyver
  • Members
  • Pip
  • Newbie
  • 5 posts
  • LocationUK

Posted 13 June 2006 - 09:33 AM

Hi I'm after some help to convert web addresses in some text body to hyperlinks.

So a user may enter [a href=\"http://www.phpfreaks.com\" target=\"_blank\"]http://www.phpfreaks.com[/a] into a text area. When the text is then displayed I want to go through and convert these to hyperlinks. Ideally would do it if the user missed off the http:// and typed www.phpfreaks.com.

I guess I need a reg expression but I need pointing in the right direction

Cheers

Mac

#2 joquius

joquius
  • Members
  • PipPipPip
  • Advanced Member
  • 319 posts

Posted 13 June 2006 - 09:37 AM

here's what I would use:

preg_replace("/(http\:\/\/[^[::space::]]+)/", "<a href=\"\\1\">\\1</a>", $text);
z..z..z..z..z..z..z..z..

#3 macgyver

macgyver
  • Members
  • Pip
  • Newbie
  • 5 posts
  • LocationUK

Posted 13 June 2006 - 11:03 AM

Thanks for that. However, I couldn't get it to work. I managed to find the following which works like a dream.

preg_replace("/[^\"'=]((http|ftp|https):\/\/[^\s\"']+)/i", "<a href=\"\\1\">\\1</a>", $text);


#4 joquius

joquius
  • Members
  • PipPipPip
  • Advanced Member
  • 319 posts

Posted 13 June 2006 - 11:11 AM

sorry mistake in the code shouldn't have put \: i suppose.
z..z..z..z..z..z..z..z..




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users