I am making register script and I need to protect string from characters other than a-z, A-Z, 0-9, and _. Is there simple way to e.g. search string for characters that are NOT in my array of allowed characters?
CodePudding user response:
You could perform a search with a regular expression:
preg_match_all('/[^A-Za-z0-9_]/', $string, $matches);
See preg_match_all for more details.
Basically you are searching for characters, which are not present in the indicated list. The matches are stored in $matches.
If the returned array is empty, the string passes, otherwise the array contains the disallowed characters.
CodePudding user response:
This is usually done by means of a regular expression, which allows to search within sets of characters:
<?php
$input = [
"abcde",
"XXX111XXX",
"o",
"l#QW E, ???P#WE094<SDF",
"```",
"GGGG#",
"",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
];
$output = array_filter($input, function($value) {
return preg_match('/^[a-zA-Z0-9] $/', $value);
});
var_dump($output);
The output obviously is:
array(4) {
[0]=>
string(5) "abcde"
[1]=>
string(9) "XXX111XXX"
[2]=>
string(1) "o"
[7]=>
string(62) "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
}
