作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我试图匹配很多年表的 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/
我是一名优秀的程序员,十分优秀!