Следующий код не дает ожидаемых результатов, хотя и должен. Но если вы прокомментируете шаблон, который использует комментарии и использует однострочную версию, он работает. Можете ли вы подумать, что может быть проблемой?
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";
}
Повторение шаблона в предварительном теге приводит к следующему:
/^
(?=[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
У вас нет новой строки после комментариев, которые вы заканчиваете, с одной цитатой для конкатенации внутри кавычек, чтобы следующая строка отображалась как часть комментария. Затем вы получите открытую фигурную скобу, которая приведет к плохой схеме.
Это работает?
'/^
(?=[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';