Search code examples
phpregexpreg-match

Validate url with array paramter in php?


I am trying to add preg_match validation for a URL like:

http://test.com/page/?param1[0=a&param2[1]=b

If you see in above example one square bracket is missing.


Solution

  • Checking with two regex, may this works for you

    $website = 'http://test.com/page/?param1[0=a&param2[1]=b';
    
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website) || !preg_match("/^[^\[\]]*+(\[(?>[^\[\]]|(?1))*+\][^\[\]]*+)*$/",$website)) {
        echo "Invalid URL"; 
    }else{
        echo 'valid';
    }
    

    O/p: Invalid URL

    The only problem with this check is It only check bracket unbalance, not its position.