2

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

2
  • Also i want variable in array array('page'=>1,'sort'=>'desc','param'=5,'param2'=25) Commented Oct 13, 2010 at 13:30
  • I think preg_match will work but i want exact regular expression Commented Oct 13, 2010 at 13:31

5 Answers 5

10

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

Yes, but order of the parameter can be change
@Rahul I don't recall you specifying that in your question
Don’t use a generic .+ if you can use a more specific [^&]+.
0

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

Comments

0

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

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.