检查它是否包含除字母数字或空格以外的任何内容


PHP Check if it contains anything but alphanumerical, or spaces

我有一个发送字符串的表单。就像这样简单:

<form action="test2.php" method="POST">
String: <input type="text" name="string" />
<br /><input type="submit" value="Send >" />
</form>
下面是test2.php:
<?php
$string = $_POST['string'];
preg_replace("/[^0-9a-zA-Z ]/", "", $string {
echo "You can't have any symbols in your username.";
} else {
echo "Nice string!";
}
?>

它不工作。我试图这样做,如果字符串包含任何BUT字母数字字符或空格,(所以任何其他符号),它会说你不能有符号。但如果它只包含字母数字或空格,它将显示Nice String。

我如何做到这一点?

您的语法完全无效。您需要这样的内容:

<?php
$string = $_POST['string'];
if ( preg_match("/[^0-9a-zA-Z ]/", $string) ) {
    echo "You can't have any symbols in your username.";
} else {
    echo "Nice string!";
}
?>

请注意,我使用preg_match来测试regex是否匹配,而不是preg_replace,它替换了字符串的部分。