gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:02:09 27 4
gpt4 key购买 nike

我试图匹配很多年表的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com