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) ) {
	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?

Recommended Answers

All 2 Replies

at the end of your first regex you have: ...(\#[-a-z!//\d_]*)?$/i Try escaping those slashes: ...(\#[-a-z!\/\/\d_]*)?$/i ALSO, instead of:

try using apostrophes:

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.


$valid_protocol = "~^http://|https://~i";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.