简体   繁体   中英

Match to the end of the string in PHP

Given a string and regex, how can I make sure it matches the entire string? That is, I don't want a newline to trigger the end of the match - I want it to match to the very end of the string.

Example:

<?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.";
}

Use the 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";

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM