有人可以用preg_match帮我吗?这有什么问题?

时间:2016-11-08 18:52:37

标签: php

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo "Homework1_1"?></title>
</head>
<body>

<form action="" method="post">
<input name ="name" type = "text" placeholder="Type your Name">
<input name = "age" type = "text" placeholder = "Type your age">
<input type = "submit">
</form>
<?php
if(isset($_POST["name"])){
$Name =["name"];
$Age = ["age"];
if(preg_match("[0-10]", $name)){
    echo "Failed, name can not be number";
}
 if(preg_match("/[a-zA-Z + ] +/",$ar)){
    echo "Failed, age cannot have letter";
}
if((!preg_match("[0-10]", $Name))&&(!preg_match("/[a-zA-Z + ] +/",$Age))){
    echo "Welcome! Your name is $Name and you are $Age years old";
}   
}
 ?>
</body>
</html>

这是我的程序代码。 我想如果我在$ Name = [“name”]中写号码或者在$ Age = [“age”中写一个字母,网站会显示一个错误信息,就像在块中一样,但是当我运行代码并输入一些值给两者盒子,网站每次都显示我

  

警告:preg_match()期望参数2为字符串,给定的数组为   C:\ XAMPP \ htdocs中\ php_workshop_1_citat \ GrundOvningar \ homework1_1_post.php   第18行

     

警告:preg_match()期望参数2为字符串,给定的数组为   C:\ XAMPP \ htdocs中\ php_workshop_1_citat \ GrundOvningar \ homework1_1_post.php   在第21行

     

警告:preg_match()期望参数2为字符串,给定的数组为   C:\ XAMPP \ htdocs中\ php_workshop_1_citat \ GrundOvningar \ homework1_1_post.php   在第26行

     

警告:preg_match()期望参数2为字符串,给定的数组为   C:\ XAMPP \ htdocs中\ php_workshop_1_citat \ GrundOvningar \ homework1_1_post.php   在第26行

     

注意:数组转换为字符串   C:\ XAMPP \ htdocs中\ php_workshop_1_citat \ GrundOvningar \ homework1_1_post.php   在第27行

     

注意:数组转换为字符串   C:\ XAMPP \ htdocs中\ php_workshop_1_citat \ GrundOvningar \ homework1_1_post.php   在第27行

     

欢迎!你的名字是Array,你已经是Array岁了

我做错了什么?也许我不需要使用preg_match?如果是这样,我该怎么办?

2 个答案:

答案 0 :(得分:3)

PHP变量区分大小写

if(isset($_POST["name"])) {
  $name = $_POST["name"];
  $age = $_POST["age"];
  if(preg_match("[0-10]", $name)){
    echo "Failed, name can not be number";
  }
  if(preg_match("/[a-zA-Z + ] +/", $age)) {
    echo "Failed, age cannot have letter";
  }
  if((!preg_match("[0-10]", $name)) && (!preg_match("/[a-zA-Z + ] +/",$age))) {
    echo "Welcome! Your name is $Name and you are $Age years old";
  }   
}

答案 1 :(得分:1)

您的代码错误

$name =["name"];
$age = ["age"];

应该是

$name = $_POST["name"];
$age = $_POST["age"];

另外,你的preg_match应该是:

对于数字:

preg_match("/[0-9]/", $name)

对于信件:

preg_match("/[a-zA-Z]/", $age)