Regular expression for allowed characters

放肆的年华 提交于 2019-12-25 18:45:38

问题


i need to check, if the string in my PHP code contains only a specified list of characters. But as some of them might need scape, i just can't get it to work. I have tried everything, but it just doesen't work...

The required validation is:

  • 0-9
  • A-Z
  • a-z
  • chars: .%^&()$#@!/-+/

Basicaly, i want to check if there is an unknown ascii character (i don't know if there is a function to do that already).

My code is like this now:

if(preg_match("/[A-Za-z0-9\.\#\-\+\*\\\/\=\_\%\$\(\)]/", $cmd) === false)

So, all of the chars are special?


回答1:


You might be missing a * at the end of the regexp. Also you could instead have the set expressed like [\x00-\x7F] (taken from here).

This should work:

[\x00-\x7F]*



回答2:


No, all of those characters are not special. If you're unsure, you can let PHP do the escaping for you with preg_quote():

$regex = '/[A-Za-z0-9' . preg_quote( '.%^&()$#@!/-+/', '/') . ']+/';
if( !preg_match( $regex, $cmd))

Also, preg_match() returns an int, and you're doing === on a boolean, which will never hold true, since they will never be of the same type. You can simply check for if( !preg_match()).




回答3:


if(preg_match("/[.%^&()$#@!/+-a-zA-Z\d\s]+/", $cmd) === false) and if you need anchors if(preg_match("/^[.%^&()$#@!/+-a-zA-Z\d\s]+$/", $cmd) === false)



来源:https://stackoverflow.com/questions/11811301/regular-expression-for-allowed-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!