Rahul
Rahul

Reputation: 2731

Regular expression for fixed string

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

Upvotes: 2

Views: 2462

Answers (5)

ant
ant

Reputation: 22948

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

Upvotes: 1

Mike Dinescu
Mike Dinescu

Reputation: 55730

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;

Upvotes: 0

Hannes
Hannes

Reputation: 8237

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

Upvotes: 0

The Archetypal Paul
The Archetypal Paul

Reputation: 41769

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

Upvotes: 0

Alin P.
Alin P.

Reputation: 44346

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.

Upvotes: 10

Related Questions