randy back randy back - 1 year ago 69
PHP Question

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

I use PHP.


$string = "Hello world!";

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 Source


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:


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


And so on...

Some more help here: PhpRegExp

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download