Unknown modifier in regular expression [duplicate]

痴心易碎 提交于 2019-12-02 17:14:49

问题


Does anyone knows why i receive this error : preg_match() [function.preg-match]: Unknown modifier '(' using this method:

function checkFBDateFormat($date) {
    if(preg_match ("/^([0-9]{2})/([0-9]{2})/([0-9]{4})$/", $date, $parts)){
        if(checkdate($parts[2],$parts[1],$parts[3]))
            return true;
        else
            return false;
    } else {
        return false;
    }
}

回答1:


You did not escape your "/" and you didn't complete your if statements either, please try this:

        function checkFBDateFormat($date) {
        if(preg_match("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/", $date, $parts)){
            if(checkdate($parts[2],$parts[1],$parts[3])) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

echo var_dump(checkFBDateFormat('08/09/2012'));



回答2:


If the first char is e.g. an slash / is detected as delimiter fro the regular expression. Thus your regex is only the part ^([0-9]{2}). And everything after the second slash is recognized as modifiers for the regex.

If you really want to match a slash, use \/ to escape it




回答3:


Since you are using slash in regular expression, need use other delimiter, try:

preg_match ("#^([0-9]{2})/([0-9]{2})/([0-9]{4})$#", $date, $parts)



回答4:


You need to escape your slash, like so:

if(preg_match ("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/", $date, $parts)){



回答5:


You use / as delimiter for your expression. However, it's completely unnecessary anyway

$parts = explode('/', $date);

Even better: http://php.net/datetime.createfromformat

To give you an idea what happens: PCRE regular expression require a delimiter at the start and the end of the pattern itself. Everything after the second delimiter is treated as modifier. Thus you decided to use / as delimiter (it's always the first character), so your pattern ended right after /^([0-9]{2})/. Everything next (which is a ( at first) is treated as modifier, but ( is not an existing modifier.

If you want to stay with regular expression, I recommend to use another delimiter like

~^([0-9]{2})/([0-9]{2})/([0-9]{4})$~
#^([0-9]{2})/([0-9]{2})/([0-9]{4})$#

Just read the manual about the PCRE-extension

Two additional comments:

  • You should define $parts, before you use it
  • Remember, that the expression is quite inaccurate, because it allows dates like 33/44/5678, but denies 1/1/1970



回答6:


You might want to consider not using regular expressions at all.

<?php
// simple example
$timestamp = strtotime('12/30/2012');
if ($timestamp) {
    // valid date… Now do some magic
    echo date('r', $timestamp);
}


来源:https://stackoverflow.com/questions/12493489/unknown-modifier-in-regular-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!