How can I get a string containing only z to z, A to Z, 0 to 9, and some characters?
You can check your string (let $str ) with preg_match :
$str
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 ]
]
You can filter it like this:
$text = preg_replace("/[^a-zA-Z0-9]+/", "", $text);
As for some characters , you should be bigger
No regular expression needed, you can use Ctype functions:
Ctype
ctype_alnum
ctype_alpha
ctype_cntrl
ctype_digit
ctype_graph
ctype_lower
ctype_print
ctype_punct
ctype_space
ctype_upper
ctype_xdigit
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
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.
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);
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
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!