preg_match在php中无法正确匹配

时间:2013-09-13 23:56:29

标签: php regex if-statement preg-match

无法理解这里发生了什么。代码中的注释解释。提前致谢。为了更容易阅读,一些代码位丢失就像写入DB部分一样。但问题与这些问题是分开的。

if (filter_var($email, FILTER_VALIDATE_EMAIL) == TRUE and 
preg_match("/^[\w ]+$/", $address_one) == TRUE and 
preg_match("((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20})", $password) == TRUE) {
//When given a valid email/address/password the code successfully gets to this point and inserts into a DB

} else {
    //When it fails validation with an invalid email/password/address it drops in here
    //but then it doesn't change error code variable...
    $errorcode = "IHAVENOTCHANGED";
    if (filter_var($email, FILTER_VALIDATE_EMAIL) == FALSE) {
            $errcode = " email,";
    }
    if (preg_match("/^[\w ]+$/", $address_one) == FALSE) {
            $errcode = " address line 1,";
    }
    if (preg_match("((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20})", $password) == FALSE) {
            $errcode = " password,";
    }
    writetolog("LoginCreation", "Login failed due to invalid input: " . $errorcode . " - user: " . $email);
    echo "Invalid data for $errorcode please try again -- ADDRESS=$address_one -- EMAIL=$email -- PASS=$password";

}

2 个答案:

答案 0 :(得分:1)

除了其他答案已经解决的问题之外,要验证表单数据,请考虑分离关注点。想想,你有必须通过一些规则的领域,这是前提。这是一个简单的例子。免费codez!

// Your rules can be regex or functions
$rules = [
  'text' => '/^[\w ]+$/',
  'pass' => '/((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20}/',
  'email' => function($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
  }
];

function validate($value, $rule)
{
  $rule = $rules[$rule];

  // A function
  if (is_callable($rule)) {
    return call_user_func($rule, $value);
  }

  // A regex
  return preg_match($rule, $value);
}

// Usage:

// field => rule
// Use the `name` of your input in the markup
$fields = [
  'email' => 'email',
  'address' => 'text',
  'password' => 'pass'
];

// field => error
$errors = [
  'email' => 'Please enter a valid email',
  'address' => 'Please enter a valid address',
  'password' => 'Please enter a valid password'
];

// Get data from $_POST

$html = [];

foreach ($_POST as $field => $value) {
  // We confirm that this is a field we want to process
  if (isset($fields[$field])) {
    // Did it fail validation?
    if ( ! validate($value, $fields[$field])) {
      $html []= '<li class="error">'. $errors[$field] .'</li>';
    }
  }
}

// Print list of errors if any
if ( ! empty($html)) {
  echo '<ul id="errors">'. implode('', $html) .'</ul>'
}

exit;

答案 1 :(得分:0)

您有两个不同的变量$errorcode$errcode,并且正在writetolog()来电中使用前者。如果将这些行放在代码的顶部(并删除$errorcode = "IHAVENOTCHANGED";),PHP应该抱怨使用未定义的变量:

error_reporting(-1);
ini_set('display_errors', true);

你还需要用分隔符包围正则表达式模式 - 即/个字符,如@elclanrs所述。