2014-11-06 15 views
0

即使它應該,下面的代碼也不會產生預期的結果。但是,如果您評論使用註釋並使用單行版本的模式,它確實有效。你能想到可能是什麼問題嗎?帶註釋的正則表達式不起作用

define('USER_PASSWORD_MIN_LENGTH', 8); 
define('USER_PASSWORD_MAX_LENGTH', 15); 

$password = 'mlk45jl64pfw'; 

//$pattern = '/^(?=[a-zA-Z]*?\d)(?=\d*?[a-zA-Z])[a-zA-Z\d]{8,15}$/x'; 
///* 
$pattern = '/^ 
      (?=[a-zA-Z]*?\d)    # Checks if the string contains at least one digit 
      (?=\d*?[a-zA-Z])    # Checks if the string contains at least one letter either in lower- or upper-case 
      [a-zA-Z\d]{      # Overall the string must consist of only digits and letters, regardless of capitalization for the latter' 
      . USER_PASSWORD_MIN_LENGTH . ', # Password minimum length' 
      . USER_PASSWORD_MAX_LENGTH . '} # Password maximum length 
      $/x'; 
//*/ 


if (preg_match($pattern, $password)) { 
    echo "<p>Password is valid.</p>\n"; 
} else { 
    echo "<p>Password is not valid.</p>\n"; 
} 

回答

0

Echo'ing在此在預先標記的結果模式:

/^ 
      (?=[a-zA-Z]*?\d)    # Checks if the string contains at least one digit 
      (?=\d*?[a-zA-Z])    # Checks if the string contains at least one letter either in lower- or upper-case 
      [a-zA-Z\d]{      # Overall the string must consist of only digits and letters, regardless of capitalization for the latter8, # Password minimum length15} # Password maximum length 
      $/x 

你不必換行後,你用單引號結束意見引號內串聯所以下一行顯示爲評論的一部分。然後你最終得到開放的大括號,這會導致不好的模式。

0

這是行不通的?

'/^ 
    (?=[a-zA-Z]*?\d)     # Checks if the string contains at least one digit 
    (?=\d*?[a-zA-Z])     # Checks if the string contains at least one letter either in lower- or upper-case 
    [a-zA-Z\d]{      # Overall the string must consist of only digits and letters, regardless of capitalization for the latter 
    ' . USER_PASSWORD_MIN_LENGTH . ', # Password minimum length 
    ' . USER_PASSWORD_MAX_LENGTH . '} # Password maximum length 
    $/x';