views:

104

answers:

5

Hi friends,

I have following string.

?page=1&sort=desc&param=5&parm2=25

I need to check whether the enter string url is in strict format except variable value. Like page=, sort=, param=, param2.

Please suggest regular expression. Thanks

+9  A: 

Hi,

You should use parse_str and check if all the parameters you wanted are set with isset. Regex is not the way to go here.

Alin Purcaru
A: 

If you care about the order of parameters, something like this:

\?page=[^&]+&sort=[^&]+param=[^&]+param2=[^&]+$

But Alin Purcaru is right - use the parse_str function already written to do this

Paul
A: 

You could use the following regx /\?page=[^&]*sort=[^&]*param=[^&]*param2=/` to match:

if (preg_match("/\?page=([^&]*)sort=([^&]*)param=([^&]*)param2=([^&]*)/i", $inputstr, $matches))
{
   echo "Matches:";
   print_r($matches);     // matches will contain the params

}
else
   echo "Params nor found, or in wrong order;
Miky Dinescu
+2  A: 

Maybe this :

\?page=\d+&sort=.+&param=\d+&param2=\d+

which translates to :

?page= followed by any digit repeated 1 or more times

&sort= followed by any character repeated 1 or more times

&param= followed by any digit repeated 1 or more times

&param2= followed by any digit repeated 1 or more times

I think Alin Purcaru 's suggestion is better

EDIT:

(\?|&)(page=[^&]+|sort=[^&]+|param=[^&]+|parm2=[^&]+)

This way the order doesn't matter

c0mrade
Yes, but order of the parameter can be change
Rahul
@Rahul I don't recall you specifying that in your question
c0mrade
@Rahul take a look at my edit
c0mrade
Gumbo
A: 

The regex would be ^\?([\w\d]+=[\w\d]+(|&))*$ As long as your values are Alpha Numeric, but maybe you wanna take a look in to filters if you want to validate an url http://www.php.net/manual/en/book.filter.php

Hannes