简体   繁体   中英

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

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.

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

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

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;

正则表达式将是^\\?([\\w\\d]+=[\\w\\d]+(|&))*$只要您的值是Alpha数字,但也许您想看看过滤器是否你想验证一个网址http://www.php.net/manual/en/book.filter.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM