使用php检查带有表值的regex模式


Check regex pattern with table value using php

我有一个SQL表:

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

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

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

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

我不知道你为什么要这样存储日期。

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

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

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

试试这个代码

通过此语法,您可以检查其正则表达式模式

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

您可以通过对查询本身进行轻微修改来传递regexp。

SELECT * FROM table WHERE `date format` REGEXP '^[0-9]{2}-[0-9]{2}-[0-9]{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);
?>