问题
The site user can sign-up on a site, and during sign-up he can provide a name.
I want this name to be a valid name, and free of any HTML and other funky characters. Is strip_tags enough for this?
回答1:
I find that there's no single function for idiot-proofing user inputs. Best to mix a few together:
$val = trim($val);
$val = strip_tags($val);
$val = htmlentities($val, ENT_QUOTES, 'UTF-8'); // convert funky chars to html entities
$pat = array("\r\n", "\n\r", "\n", "\r"); // remove returns
$val = str_replace($pat, '', $val);
$pat = array('/^\s+/', '/\s{2,}/', '/\s+\$/'); // remove multiple whitespaces
$rep = array('', ' ', '');
$val = preg_replace($pat, $rep, $val);
$val = trim($val);
$val = mysql_real_escape_string($val); // excellent final step for MySQL entry
回答2:
Regex could fit well with less code:
^[A-Z]'?[- a-zA-Z]( [a-zA-Z])*$
Here we have good examples:
Regex for names
来源:https://stackoverflow.com/questions/9371486/strip-tags-enough-to-remove-html-from-string