954,587 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem with PHP preg_match

Hey,
So I made a regular expression to check for valid URLs
In Javascript I'm using the code

var valid_url = /^(https?:\/\/)?((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|((\d{1,3}\.){3}\d{1,3}))(\:\d+)?(\/[-a-z\d%_.~+]*)*(\?[;&a-z\d%_.~+=-]*)?(\#[-a-z!//\d_]*)?$/i;
var valid_protocol = /^http\:\/\/|https\:\/\//i;
	
if ( !valid_url.test(url) || url.length == 0 ) {
	$('#url_return').html('Invalid URL!');
	return false;
}

if ( !valid_protocol.test(url) ) {
	$('#input_url').val('http://'+url);
	url = $('#input_url').val();
}


}
Which works fine, but when I try using the same regular expression in PHP

$valid_url = "/^(https?:\/\/)?((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|((\d{1,3}\.){3}\d{1,3}))(\:\d+)?(\/[-a-z\d%_.~+]*)*(\?[;&a-z\d%_.~+=-]*)?(\#[-a-z!//\d_]*)?$/i";
$valid_protocol = "/^http\:\/\/|https\:\/\//i";
$Error = false;

$Input['TARGET_URL'] = urldecode($Input['TARGET_URL']);

if ( !preg_match($valid_url, $Input['TARGET_URL']) or strlen($Input['TARGET_URL']) == 0 ) {
	$Output = array('status'=>'error', 'type'=>'Invalid input URL', 'code'=>'251');
	$Error = true;
}

if ( !preg_match($valid_protocol, $Input['TARGET_URL']) ) {
	$Input['TARGET_URL'] = 'http://'.$Input['TARGET_URL'];

I get the error
Warning: preg_match() [function.preg-match]: Unknown modifier '/' in /path/to/file.php on line 10
(Line 10 is if ( !preg_match($valid_url, $Input['TARGET_URL']) or strlen($Input['TARGET_URL']) == 0 ) { )

Why is this problem only in PHP?
-Sam

samarudge
Posting Whiz
359 posts since May 2008
Reputation Points: 26
Solved Threads: 31
 

at the end of your first regex you have:
...(\#[-a-z!//\d_]*)?$/i

Try escaping those slashes: ...(\#[-a-z!\/\/\d_]*)?$/i

ALSO, instead of:
$valid_url="...";

try using apostrophes:
$valid_url='...';

hielo
Veteran Poster
1,124 posts since Dec 2007
Reputation Points: 116
Solved Threads: 244
 

Another way is not to use the / as the regex delimiter (in PHP). You can use any character, e.g. ~ or %. That way you won't have to escape the slash.

Example:

$valid_protocol = "~^http://|https://~i";
pritaeas
Posting Expert
Moderator
5,484 posts since Jul 2006
Reputation Points: 653
Solved Threads: 875
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You