dsvyc66464
2015-01-07 18:25
浏览 123
已采纳

匹配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
"; // OOPS - this will match
if(preg_match($pattern, $d)) {
    echo "This is a date string.";
}

图片转代码服务由CSDN问答提供 功能建议

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

示例:

 &lt;?php 
 //简化日期模式
 $ pattern =“/ ^ [0-9] {4} \  -  [0-  9] {2} \  -  [0-9] {2} $ /“; 
 $ d =”2014-01-05 
“;  // OOPS  - 这将匹配
if(preg_match($ pattern,$ d)){
 echo“这是一个日期字符串。”; 
} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douyunhuan9886 2015-01-07 18:30
    已采纳

    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";
    
    已采纳该答案
    打赏 评论
  • dougou3871 2015-01-07 18:29

    You would need to use the multi-line pattern modifier m like this:

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

相关推荐 更多相似问题