php - 如何在 MYSQL 中使用 REGEXP 来匹配数组中的日期?

标签 php mysql regex laravel

我试图匹配很多年表的 publication_date 中的年份。我正在使用 Laravel (PHP)。

我写过这样的东西:

if($this->request->has('publication_years')){
    $years = implode('-[0-9]{2}-[0-9]{2}|', explode(',', $this->request->get('publication_years'))) . '-[0-9]{2}-[0-9]{2}';

    $model = $model->whereExists(function ($query) use ($years)
    {
        $query->select(DB::raw(1))
            ->from('patent')
            ->whereRaw('patent.id = document.documentable_id')
            ->whereRaw('document.documentable_type = "patent"')
            ->whereRaw('(patent.publication_date REGEXP (' . $years . '))');
    });
}

岁月如?publication_years=2015,2016。我使用 , 分隔符分解它们,然后分解它们以匹配日期的方式制作 REGEXP 模式。此后几年的转储就像 2015-[0-9]{2}-[0-9]{2}|2016-[0-9]{2}-[0-9]{2

这在 http://regexr.com/ 工作但我仍然遇到错误,所以我猜测 MYSQL 还存在一些其他语法。我看到的错误是:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[0-9]{2}-[0-9]{2}|2016-[0-9]{2}-[0-9]{2})))' at line 1 (SQL: select count(*) as aggregate from `document` where exists (select * from `folder` where `document`.`folder_id` = `folder`.`id` and (exists (select * from `user` inner join `accessible_by_user` on `user`.`id` = `accessible_by_user`.`user_id` where `accessible_by_user`.`accessible_id` = `folder`.`id` and `accessible_by_user`.`accessible_type` = folder and `user_id` = 1) or exists (select * from `role` inner join `accessible_by_role` on `role`.`id` = `accessible_by_role`.`role_id` where `accessible_by_role`.`accessible_id` = `folder`.`id` and `accessible_by_role`.`accessible_type` = folder and `role_id` in (1)))) and exists (select 1 from `patent` where patent.id = document.documentable_id and document.documentable_type = "patent" and (patent.publication_date REGEXP (2015-[0-9]{2}-[0-9]{2}|2016-[0-9]{2}-[0-9]{2}))))

我做错了什么?我该如何纠正这个问题?

最佳答案

这是一种准备在 MySQL 中使用的正则表达式的方法:

$this_request_get_publication_years = "2015,2016,2017";
$years = '^(' . implode('|', explode(',',      
$this_request_get_publication_years)) . ')-[0-9]{2}-[0-9]{2}';
echo "(patent.publication_date REGEXP '" . $years . "')";
// => (patent.publication_date REGEXP '^(2015|2016|2017)-[0-9]{2}-[0-9]{2}')

REGEXP '^(2015|2016|2017)-[0-9]{2}-[0-9]{2}' 只会获取以下记录:

  • ^ - 在字符串的开头,有...
  • (2015|2016|2017) - 3 年中的任意一年(肯定会支持更多)
  • -[0-9]{2} - 连字符后跟 2 位数字
  • -[0-9]{2} - 同上。

后两个子模式可以收缩为 (-[0-9]{2}){2}

关于php - 如何在 MYSQL 中使用 REGEXP 来匹配数组中的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38502413/

相关文章:

c++ - QSql数据库 : QMYSQL driver not loaded on Mac OS

PHP MySQL 更新查询不适用于变量

python正则表达式拆分字符串,同时保持分隔符与值

javascript - 由句点分隔的 3 个 3 位数值的正则表达式

php - Laravel 更新查询数组到字符串转换

php - 将 URL 提交到没有 "http://"、有 "www."或两者都没有的表单中

php - 使用 CURL 获取 JSON 数据

php - 使用准备好的语句时如何将参数传递给 "WHERE IN"查询?

mysql - 在一个查询中返回多个选定值?

regex - 如何使用sed用逗号替换空格?