Jump to content

[SOLVED] detecting url in string


AndyB

Recommended Posts

I want to check user-entered comments for any url whether or not it contains http ftp or www, i.e. visitthis.tld should be caught as well as fully-qualified urls.  I don't need to convert them to anything, just detect their presence so that I can reject the user string.

 

I *think* regex can do it, but that's the full extent of my regex knowledge.  Code suggestions, please.

 

Link to comment
https://forums.phpfreaks.com/topic/62581-solved-detecting-url-in-string/
Share on other sites

The following will catch fully-qualified URLs.  It's very general and can include any protocol including http, ftp, https, news, and any other that I can't think of.  \S+ is any non-whitespace characters, again very general, but the specificity of the "://" sequence should be enough to tell if it's a URL.

 

|[a-z0-9+.-]+://\S+|i

 

This should catch any URL without the URI.  This is very general as well.  At least one part domain name followed by a period (\w+\.), such as "example.".  "\w{2,6}" represents the tld ("com").  "\S*" is zero or more non-whitespace ("/~user/file.php").

 

example.com/~user/file.php

 

/(?:\w+\.)+\w{2,6}\S*/

 

Is that general/specific enough for your needs?  (These are PCREs for use in the preg_* functions.)

 

Edit:  You can combine them:

 

~(?:[a-z0-9+.-]+://)?(?:\w+\.)+\w{2,6}\S*~i

Sure.

 

<?php

if (preg_match('~(?:[a-z0-9+.-]+://)?(?:\w+\.)+\w{2,6}\S*~i', $mystring)) {
echo "no links, you turkey";
} else {
echo "nice comment";
}

?>

 

Or if you want it commented:

 

<?php

if (preg_match('~
	(?:[a-z0-9+.-]+://)?  # A optional resource (http, ftp, etc)
	(?:\w+\.)+            # the host.domain
	\w{2,6}               # the TLD
	\S*                   # an optional path/to/file
	~ix', $mystring)) {
echo "no links, you turkey";
} else {
echo "nice comment";
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.