Jump to content
MakeWebGames

Recommended Posts

Posted (edited)

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*)?@)?(?:(?!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?

Thanks

**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
Posted
filter_var() allows a number of urls I deem not valid for my purpose, thanks though

What kind do you deem valid for purpose, then?

Tell us your rule set, and we'll regex that

Posted

My Regex is also sub par:

<?php

$urls = array (
   'a',
   'http://a',
   'www.a',
   'test.com',
   'http://test.com',
   'http://www.test.com',
   'http://www.test.com?searchblah&blajjj',
   'http://www.te$%^$.com',
   'http://test.1223',
   'http://test.co',
   'http://test.co.uk',
   'http://sub.test.com',
);


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 )

Posted (edited)

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

Join the conversation

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

Guest
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...