匹配到 PHP 中字符串的末尾

Match to the end of the string in PHP

给定一个字符串和正则表达式,我如何确保它匹配整个字符串?也就是说,我不希望换行符触发匹配结束 - 我希望它匹配到字符串的末尾。

示例:

<?php
// simplified date pattern
$pattern = "/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}$/";
$d = "2014-01-05\n"; // OOPS - this will match
if(preg_match($pattern, $d)) {
    echo "This is a date string.";
}

您需要像这样使用多行模式修饰符 m

$pattern = "/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}$/m"; // note m at end after pattern

使用D modifier:

D (PCRE_DOLLAR_ENDONLY)
If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines).

$pattern = "/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}$/D";