So here is what I'm doing exactly:
I have a form with a caption on the right of it, I want to write in the form only A-Z,0-9 and whi开发者_如何转开发tespaces, and for the caption I want to do the opposite, so if the user write's something wrong I can show what's the problem for example: "Invalid Charachter"
But I'm stuck with +
and #
I want to ignore them too from the form with regular expression so I can show the "Invalid character"
message for these too, as I saw php thinks that + sign is = to space ( ) or what, but I need to ignore + and # signs too. This is my current code:
preg_match_all("/[^\w\s]/",$string,$matches);
foreach($matches[0] as $ic){
if(strpos($str,$ic) || $str[0] == $ic){
$fullname_error = "Invalid Character";
}
}
Valid strings:
- John Doe
- Mary Sue
Not valid strings:
- J#ohn Doe
- John&Doe
- John+Doe
- Mar@y+Sue
- !Mary Sue
- Mary Sue!
You could do something like this to handle the invalid characters:
$str = 'gum@#+boo';
if (preg_match_all('/[^\w\s]/u', $str, $matches)) {
echo sprintf(
'<p>Your input <b>%s</b> contains %d invalid character%s: <b>%s</b>.</p>',
htmlspecialchars($str),
count($matches[0]),
count($matches[0]) > 1 ? '' : 's',
implode('</b>, <b>', array_map('htmlspecialchars', array_unique($matches[0])))
);
echo '<p>Please choose a different input value.</p>';
}
Try this:
<?
function checkString($str)
{
echo "Testing ".$str."<br />";
// Check if there are invalid characters
if (!preg_match("/^[a-zA-Z0-9\s]+$/", $str))
{
echo "Oh no! There are invalid characters! :(<br />";
}
else
{
echo "There is no invalid character!!! :)<br />";
}
// What are the invalid characters?
if (preg_match("/[^(a-zA-Z0-9\s)]/", $str, $matches))
{
echo "Invalid character: ".$matches[0]."<br />";
}
}
checkString("This is a good string");
checkString("This is a not a good string$%#@#$");
?>
精彩评论