Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP字符串验证_Php_String_Forms_Validation - Fatal编程技术网

PHP字符串验证

PHP字符串验证,php,string,forms,validation,Php,String,Forms,Validation,我也一直在尝试使用PHP来验证我的表单。表单要求用户输入详细信息,一旦表单经过验证,这些信息将被输入到数据库的表中。我在表单中有一个名字字段,我正在尝试验证它,以确保它输入了一个值(强制字段),并且应该只包含字母字符或连字符(-) 以下是我到目前为止的情况: <?php if (isset($_POST["submit"])) { $flag = false; $badchar = ""; $string = $_POST["fname"]; $string = trim($string

我也一直在尝试使用PHP来验证我的表单。表单要求用户输入详细信息,一旦表单经过验证,这些信息将被输入到数据库的表中。我在表单中有一个名字字段,我正在尝试验证它,以确保它输入了一个值(强制字段),并且应该只包含字母字符或连字符(-)

以下是我到目前为止的情况:

<?php
if (isset($_POST["submit"])) {

$flag = false;
$badchar = "";
$string = $_POST["fname"];
$string = trim($string);
$length = strlen($string);
$strmsg = "";

if ($length == 0) {
$strmsg = '<span class="error"> Please enter your first name</span>';
$flag = true;}
else {
for ($i=0; $i<$length;$i++){
    $c = strtolower(substr($string, $i, 1));
    if (strpos("abcdefghijklmnopqrstuvwxyz-", $c) == false){
        $badchar .=$c;
        $flag = true;
    }
}
if ($flag) {
    $strmsg = '<span class="error"> The field contained the following invalid characters: $badchar</span>';}
}
if (!$flag) {
    $strmsg = '<span class="error"> Correct!</span>';}
}
?>

<h1>Customer Information Collection <br /></h1>

<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="custinfo" >
<table>
<tr>
    <td><label for="custid">Customer ID (integer value): </label></td>
    <td><input type="text" id="custid" name="custid" value="<?php echo $temp ?>" size=11 /><?php echo $msg; ?></td>
</tr>

<tr>
    <td><label for="customerfname">Customer First Name: </label></td>
    <td><input type="text" id="fname" name="fname" size=50/><?php echo $strmsg; ?></td>
</tr>

您的问题是您已经执行了
==false
,并且
strpos
可以返回0(第一个字符的索引),其计算结果为
false
。将
==false
==false
交换,检查值是否为布尔值false,而不是计算结果为false的值。请参阅上的“返回值”部分

要打印$badchar的值,请将行更改为

$strmsg = '<span class="error"> The field contained the following invalid characters: '.$badchar.'</span>';
$strmsg='该字段包含以下无效字符:'.$badchar';

这将把变量连接到字符串中

您的代码有一些问题

strpos()
返回文本中搜索字符串位置的基于0的索引,或者返回
false
。您需要使用
==
操作符来检查结果;否则,
0
结果将被解释为false

在错误字符串中,您将看到:
该字段包含以下无效字符:$badchar

在php中,变量只能在双引号字符串中解析出来。因为您使用单引号,所以它只会回显您输入的实际文本,而不是变量的内容。您可以切换字符串中的双引号和单引号来修复它