Powered by Blogger.

Only allow letters, numbers or spaces in PHP


In some cases, you need to format the users’ input. Here are some samples that only allow letters, numbers, or spaces in PHP. The samples use preg_replace to remove invalid chars.

1. Only allow capital letters

$text = "This is a test from WAYTOWP."; 

$newtext = preg_replace("/[^A-Z]/", "", $text); 

echo $newtext;

2. Only allow small letters

$text = "This is a test from WAYTOWP."; 

$newtext = preg_replace("/[^a-z]/", "", $text); 

echo $newtext;

3. Only allow letters

$text = "This is a test from WAYTOWP."; 

$newtext = preg_replace("/[^a-zA-z]/", "", $text); 

echo $newtext;

4. Only allow letters and spaces

$text = "This is a test from WAYTOWP."; 

$newtext = preg_replace("/[^a-zA-z ]/", "", $text); 

echo $newtext;

5. Only allow letters and spaces and.

$text = "This is a test from WAYTOWP."; 

$newtext = preg_replace("/[^a-zA-z .]/", "", $text); 

echo $newtext;

6. Only allow numbers

$text = "This is a test from WAYTOWP on 2015-06-06."; 

$newtext = preg_replace("/[^0-9]/", "", $text); 

echo $newtext;

7. Only allow letters and numbers

$text = "This is a test from WAYTOWP on 2015-06-06."; 

$newtext = preg_replace("/[^a-zA-z0-9]/", "", $text); 

echo $newtext;

No comments