var with regexp validates more than expected

I'm trying to work with PHP's filter_var function to validate some inputs from an uploaded CSV.

A couple of the values I'm working with don't fall into the built-in validation filters, so I turned to FILTER_VALIDATE_REGEXP.

I'm getting different results in PHP than I am from http://regex101.com/, where I was playing around to make sure I get my patterns right.

My issue is that some extremely basic patterns are not working for me in PHP, and filter_var is permitting strings through that do not seem to match my pattern.

Some examples:

php > $regex = array("options" => array("regexp"=>"/[a-z]+/","default"=>"false"));
php > echo filter_var("123", FILTER_VALIDATE_REGEXP, $regex);
false //this is expected
php > echo filter_var("abcd", FILTER_VALIDATE_REGEXP, $regex);
abcd //this is also expected
php > echo filter_var("abcd$", FILTER_VALIDATE_REGEXP, $regex);
abcd$ //this is the problem

I'm inclined to find my own understanding of regex at fault before I blame PHP for being broken, but I really can't figure out how special characters (and digits) are sneaking through this filter. Am I dealing with a bug here?

FWIW, I'm running PHP 5.3.3, and phpinfo() tells me it is using the bundled regex library.

First post, I apologize if I've left out any vital details. Thank you!


Because you passing abcd already so its normal to pass this string. You have to use $ sign to assert position at end of the string. And also use ^ sign to begining of the string.

^[a-z]+$

So it wont match if you use %asdasd or asdasd$ or $asdasd$ See this: https://regex101.com/r/vO1iI1/4


The regex filter passes because the regex matches part of the string. That is the only requirement. Any string with even a single letter in will pass. You need to specify that you want to match the whole string by changing the regex to /^[az]+$/ . The ^ tells PHP to match the start of the string and the $ tells it to match the end. This means you are asking for the whole string from start to end to match [az]+ .


Using FILTER_VALIDATE_REGEXP requires the input to match. In your case, you match any string which contains [az]+ somewhere. If you want to ensure, the whole string have to match your regex, you have to anchor the start/end of the regex.

There are two anchors for you.

^ matches the start of the string. So ^[az]+ would match any string, which starts with at least one alpha char.

$ matches the end of the string. So [az]$ would match any string, which ends with at least one alpha char.

If you combine this two anchors, you get your desired regex.

^[az]+$

链接地址: http://www.djcxy.com/p/16542.html

上一篇: var($ email,FILTER

下一篇: var与regexp验证超出预期