【问题标题】:Check regex pattern with table value using php使用 php 检查带有表值的正则表达式模式
【发布时间】:2013-08-19 08:08:17
【问题描述】:

我有一个 SQL 表:

date
************************
|  id   |  date format |
************************
|   1   | 2013-02-10   |
|   2   | 02-02-2013   |
|   3   | 20130202     |
************************

我想将差异(日期格式)存储在日期表中,并使用以下模式与表日期进行检查:

/^\d{2}-\d{2}-\d{4}$/

如何根据日期表中的 date format 字段检查此模式?

【问题讨论】:

  • 你可以在mysql中使用REGEXP
  • 首先,不要将您的表格称为“日期”之类的保留字。

标签: php sql regex


【解决方案1】:

我不确定你为什么这样存储日期。

我假设你的数据库是 MySQL,如果是你可以使用str_to_date 函数如下:

select `date format` from mytable where str_to_date(`date format`, '%d-%m-%Y') is not null;

请注意,此查询效率不高,因为它必须扫描每一行并应用 str_to_date 函数。

【讨论】:

  • 我不知道你为什么不使用REGEXP
  • 我想检查正则表达式模式,它不只修复日期检查,如时间日期时间字符串等...
  • @user2496644,请参阅链接文档。该函数返回DATETIME。但是,如果您特别想使用正则表达式,那么 DevZer0 的答案应该可以为您完成。
  • 解决我修复它... :D stackoverflow.com/questions/18309094/…
【解决方案2】:

试试这个代码

通过这个语法你可以检查它的regex模式

  int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

【讨论】:

    【解决方案3】:

    您可以将您的正则表达式稍加修改地传递给它自己的查询。

    SELECT * FROM table WHERE `date format` REGEXP '^[0-9]{2}-[0-9]{2}-[0-9]{4}$'
    

    【讨论】:

    • 它的工作,但我的模式在工作中无效 /^\d{2}-\d{2}-\d{4}$/
    • 您的模式包括\d mysql 无法识别的限定符
    • 但是我已经失去了这种类型的模式,所以我能做什么......?为解决
    • [0-9]替换\d
    【解决方案4】:

    我修复它...(y)

    <?php
    $pattern = '/^\d{4}$/';
    $link = mysql_connect('localhost', 'root', '');
    
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    
    if (!mysql_select_db('regex_field')) {
        die('Could not select database: ' . mysql_error());
    }
    
    $result = mysql_query('SELECT date_format FROM date');
    
    $date = array();
    $newdate = array();
    
    while ($date_row = mysql_fetch_assoc($result)) {
        $date[] = $date_row;
    }
    
    foreach($date AS $key => $value) {
        $newdate[$key] = $value['date_format'];
    }
    
    foreach($newdate as $key => $value) {
        $testexample = @preg_match($pattern, $value, $matches);
    
        if($testexample == true) {
            echo "Example & Pattern Match";
    
            exit;
        }
    }
    
    echo "Example & Pattern MisMatch";
    
    mysql_close($link);
    ?>
    

    【讨论】:

    • 不要使用@ 符号。 read this
    • 除了 DevZer0 的评论,mysql_ 函数已被弃用,请开始查看mysqliPDO
    猜你喜欢
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    相关资源
    最近更新 更多