1

所以这就是我正在做的事情:

我有一个右侧有标题的表格,我想在表格中只写 AZ、0-9 和空格,而对于标题我想做相反的事情,所以如果用户写错了我可以显示有什么问题 for example: "Invalid Charachter"

但是我被困住了+#我也想从带有正则表达式的表单中忽略它们,所以我也可以显示这些"Invalid character"消息,因为我看到 php 认为 + 符号是 = 到空格()或什么,但我需要也忽略 + 和 # 符号。这是我当前的代码:

preg_match_all("/[^\w\s]/",$string,$matches);


foreach($matches[0] as $ic){
     if(strpos($str,$ic) || $str[0] == $ic){
          $fullname_error = "Invalid Character";
     }  
}

有效字符串:

  • 约翰·多伊
  • 玛丽苏

无效字符串:

  • J#ohn Doe
  • 约翰与多伊
  • 约翰+多伊
  • Mar@y+Sue
  • !玛丽苏
  • 玛丽苏!
4

2 回答 2

1

试试这个:

<?
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$%#@#$"); 
?>
于 2010-07-04T10:27:28.153 回答
1

您可以执行以下操作来处理无效字符:

$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>';
}
于 2010-07-04T11:21:47.823 回答