randy back randy back - 11 days ago 6
PHP Question

How can I make a string only use numbers and letters and certain symbols?

I use PHP.

Example:

$string = "Hello world!";
if(!safeString()){
setBlocked(true);
}

function safeString(){
//check string
}


In safeString() I want to check the these following qualities:

The string can only have:


  • Letters

  • Numbers

  • Only these symbols (!@#$%^&*/)



If it contains any other non-allowed character, it will be blocked.

How can I do this?

Answer

try:

function safeString($input){
   if( preg_match("/[^0-9a-zA-Z!@#\$%\^&\*\/]/",$input) ) return false;
   return true;
}

Be careful with accented characters (áéíóú) and stuff like that, if you want them in, you could modify the preg_match first param as:

"/[^0-9a-zA-Z!@#\$%\^&\*\/áéíóú]/"

if you wan spaces to be allowed you could add "\s":

"/[^0-9a-zA-Z!@#\$%\^&\*\/\s]/"

And so on...

Some more help here: PhpRegExp