Problem:
How do I determine if a string contains only allowed characters?
Solution (code snippet):
The following PHP example code will check if a string contains only characters in a white-list. It should be pretty easy to convert this to other languages.
function containsOnly($string, $whiteliststring){
$char_arr = str_split($string);
$whitelist_arr = str_split($whiteliststring);
foreach($char_arr as $char){
if(in_array($char, $whitelist_arr)==false) return false;
}
return true;
}
Example usage of this would be, for instance, checking for numbers only:
$numbers = "0123456789";
$not_only_numbers = "abcd123";
$only_numbers = "123";
echo containsOnly($not_only_numbers, $numbers)?"yes":"no"; // no
echo containsOnly($only_numbers, $numbers)?"yes":"no"; // yes
Code explained:
The containsOnly function uses str_split to convert strings into arrays containing their characters. The loop checks to see if any of the test string characters is absent from the white-list.
This code can generally be sped up by using an implementation of a set rather than arrays.
No comments:
Post a Comment