选中空格的文本框

时间:2013-08-09 01:10:55

标签: php

如果文本框包含空格或连字符,我需要帮助代码输出错误。我有以下内容:

elseif($_REQUEST['students']['FIRST_NAME']!= "CONTAINS SPACE OR HYPHENS")
{
    $insert_error = 'No spaces, hyphens, or spaces allowed in first name';
}

我可以使用什么功能?我还有其他适用于类似任务的功能,例如:

elseif($_REQUEST['students']['PASSWORD']!=$_REQUEST['verify_password'])
{
    $insert_error = 'Passwords did not match.';
}

我知道这很直接,但我不确定要使用什么。原谅我,我很生气。

2 个答案:

答案 0 :(得分:3)

使用正则表达式和preg_match()函数。

if ( preg_match('/[\s-]/', $_REQUEST['students']['FIRST_NAME']) ) {
  $insert_error = 'You cannot enter spaces or dashes';
}

[\s-]内的preg_match()称为正则表达式。 \s适用于任何空格字符,而-适用于短划线。

此处提供更多信息:http://php.net/manual/en/function.preg-match.php

答案 1 :(得分:-2)

$first_name = $_REQUEST['students']['FIRST_NAME'];
elseif((preg_match("/\\s/", $first_name) === true)
")
{
    $insert_error = 'No spaces, hyphens, or spaces allowed in first name';
}