Sometimes you are given a string (someone’s name, or some title, or something completely different) and you cannot afford to use this string if you’re not completely sure what to expect. For instance, sometimes you need to convert a string into something that consists only of alphanumerical characters and spaces. You can always use the following function:
/**
* create a string that only consists of alphanumerical characters and spaces
* @param $string
* @return string
*/
function createSafeString($string) {
$string = strtolower($string);
$output = "";
for ($i = 0; $i < strlen($string); $i++) {
$ord = ord($string[$i]);
if (($ord >= 48 && $ord <= 57) || ($ord >= 65 && $ord <= 90) || ($ord >= 97 && $ord <= 122) || ($ord == 32)) {
$output .= $string[$i];
}
}
return $string;
}