Allow only [az] [AZ] [0-9] per line using PHP

How can I get a string containing only z to z, A to Z, 0 to 9, and some characters?

+6
php regex
source share
7 answers

You can check your string (let $str ) with preg_match :

 if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) { // string only contain the a to z , A to Z, 0 to 9 } 

If you need more characters, you can add them before ]

+24
source share

You can filter it like this:

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

As for some characters , you should be bigger

+24
source share

No regular expression needed, you can use Ctype functions:

In your case, use ctype_alnum , for example:

 if (ctype_alnum($str)) { //... } 

Example:

 <?php $strings = array('AbCd1zyZ9', 'foo!#$bar'); foreach ($strings as $testcase) { if (ctype_alnum($testcase)) { echo 'The string ', $testcase, ' consists of all letters or digits.'; } else { echo 'The string ', $testcase, ' don\'t consists of all letters or digits.'; } } 

Online example: https://ideone.com/BYN2Gn

+7
source share

Why are these “symbols” there in the first place? It looks like you are reading text from a source that is encoded as UTF-16, but you are decoding it as something else, like latin1 or ASCII.

+2
source share

Both of these regular expressions should do this:

 $str = preg_replace('~[^a-z0-9]+~i', '', $str); 

Or:

 $str = preg_replace('~[^a-zA-Z0-9]+~', '', $str); 
+1
source share

The best and most flexible way to achieve this is by using regular expressions. But I'm not sure how to do this in PHP, but this article may help. link

0
source share

The shortcut will look like this:

 if (preg_match('/^[\w\.]+$/', $str)) { echo 'Str is valid and allowed'; } else echo 'Str is invalid'; 

Here:

 // string only contain the a to z , A to Z, 0 to 9 and _ (underscore) \w - matches [a-zA-Z0-9_]+ 

Hope this helps!

0
source share

All Articles