Mailto or URL, but not both!

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

Mailto or URL, but not both!

Post by Todd_Z »

I have a script that goes through a page and converts any valid urls to links starting with http:// and any valid email addresses to links to mailto:address. However, when I have something like email@site.com, it converts it both as a mailto and a url (site.com) This causes catastrophes. Does anyone have simple code for converting a conversation into hyperlinked text? Thanks!
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

I cant see your code but since you're a DIY kinda person (I think :?) I'll give you a pointer to try playing with.

Neagtive Lookbehinds could help here (checking for @).

They work like this (this is very pseudo) ...

Code: Select all

/(?<!foo)bar/

Code: Select all

/(?<!@)site.com/
The opposite (not needed here) is positive lookbehinds

Code: Select all

/(?<=foo)bar/
One downside to Lookbehinds is that they are fixed width. In other words, only a pattern with a fixed length can be used inside the (?<! ) group. (?<!\w{2,5}) is NOT allowed for example, but (?<=\w{5}) is.
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

something fishy is awry here.

wouldn't be for the chat thingy would it? :wink:
User avatar
Todd_Z
Forum Regular
Posts: 708
Joined: Thu Nov 25, 2004 9:53 pm
Location: U Michigan

Post by Todd_Z »

You caught me burrito - but you did it js wise, im rockin the php scriptin. Thats for the help d11
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

great that is!

send me your changes you must :P
User avatar
Todd_Z
Forum Regular
Posts: 708
Joined: Thu Nov 25, 2004 9:53 pm
Location: U Michigan

Post by Todd_Z »

Code: Select all

$msg = preg_replace( "#(?<!@)(?:http://)?((?:www\.)?\w+\.\w+)#i", "<a href=\"http://$1\">$1</a>", $msg );
Problem: name@gmail.com
returns name@g<a href=\"http://mail.com\">mail.com</a>

Code: Select all

$msg = preg_replace( "#([a-z0-9_.-]+@[a-z0-9-]+.[a-z0-9-.]+)#i", "<a href=\"mailto:$1\">$1</a>", $msg );
^^^ Seems to work well.
Post Reply