dongpu3347 2014-07-31 22:17
浏览 85
已采纳

如何使用PHP检查给定格式的字符串?

I have many headlines in my project like:

00.00.2014 - Headline Description e.t.c.

I want to check with php if the given strings contain the format 00.00.0000 - in front. The part after the - doesn't matter.

Can someone help me with something like:

$format = '00.00.0000 -';

if ($string MATCHES $format IN FRONT) {
    // ...some code...
}
  • 写回答

3条回答 默认 最新

  • douxian5963 2014-07-31 22:39
    关注

    This should work:

    if (preg_match("/^\d{2}\.\d{2}\.\d{4}\s\-\s.*$/", $string) === 1) {
        // $string matches!
    }
    

    Explanation:

    • ^ is "the beginning of the string"
    • \d is any digit (0, 1, 2, ..., 9)
    • {n} means "repeated n times"
    • \. is a dot
    • \s is a space
    • \- is a minus sign
    • . is "any single character"
    • * means "repeated 0 or more times`
    • $ means "end of the string"
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?