Jump to content

Validate URL

The Spirit

Recommended Posts

Im want to validate a URL in my php script and cant quite get it working.

Im trying to use

if (preg_match($pattern, $link) === false)

I have it working in javascript but php is being a problem

Heres the Regex

(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)[email protected])?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i);


Anyone have a solution?


**edit the regex in this post gets changed by smilies inserting themselves

The regex can be seen here http://pastebin.com/4kU801pE

Edited by The Spirit
Link to comment
Share on other sites

a, http://a, http://www.a //Not Valid

http://localhost //not valid

test.com //not valid

http://test.com //valid

http://www.test.com //valid

http://www.test.com?searchblah&blajjj //valid

http://www.te$%^$.com //not valid

http://test.1223 //Not Valid

http://test.co //valid

http://test.co.uk //valid

http://sub.test.com //valid

I'm a little rusty on regex, however, try this :?

Link to comment
Share on other sites

My Regex is also sub par:


$urls = array (

foreach ( $urls as $url ) {
   echo $url.' --- '. ( preg_match ( '#^http(s)?://(www\.)?([a-z0-9_\-\.]+)\.([a-z\.]){2,5}([/\?&\#\w=]+)?$#', $url ) ? 'Valid' : 'Not Valid' ).
   '<br />';

a --- Not Valid
http://a --- Not Valid
www.a --- Not Valid
test.com --- Not Valid
http://test.com --- Valid
http://www.test.com --- Valid
http://www.test.com?searchblah&blajjj --- Valid
http://www.te$%^$.com --- Not Valid
http://test.1223 --- Not Valid
http://test.co --- Valid
http://test.co.uk --- Valid
http://sub.test.com --- Valid

Edit: Edited expression to match '=' also ( for the likes of ?blah=123 )

Link to comment
Share on other sites

Cant seem to get it working :/

This is the code im using:

else if ((!preg_match('#^http(s)?://(www\.)?([a-z0-9_\-\.]+)\.([a-z\.]){2,5}([/\?&\#\w=]+)?$#', $url))) {
			$return['error'] = true;
			$return['msg'] = 'URL not valid';
Edited by The Spirit
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...