0

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

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by pritaeas
0

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='...';

Edited by hielo: n/a

0

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";

Edited by pritaeas: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.