Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

php - Regular expression for allowed characters

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...