Laravel:转义“LIKE”条款?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22749182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: Escape "LIKE" clause?
提问by mpen
How can I escape a LIKE
clause in Laravel/Eloquent? e.g.,
如何LIKE
在 Laravel/Eloquent 中逃避条款?例如,
$search = Input::query('sSearch', '');
if($search !== '') {
$paginatedBookings->where('first_name', 'LIKE', '%' . $search . '%');
}
If $search
contains a %
or _
they need to be escaped.
如果$search
包含 a%
或_
它们需要转义。
回答by ntzm
The other answer forgets about escaping the escape character itself, here is a more robust solution:
另一个答案忘记了转义字符本身,这是一个更强大的解决方案:
/**
* Escape special characters for a LIKE query.
*
* @param string $value
* @param string $char
*
* @return string
*/
function escape_like(string $value, string $char = '\'): string
{
return str_replace(
[$char, '%', '_'],
[$char.$char, $char.'%', $char.'_'],
$value
);
}
回答by mpen
Temporary solution:
临时解决方案:
$search = Input::query('sSearch', '');
if($search !== '') {
$escSearch = Util::escapeLike($search);
$paginatedBookings->where('first_name', 'LIKE', '%' . $escSearch . '%');
$paginatedBookings->orWhere('last_name', 'LIKE', '%' . $escSearch . '%');
}
class Util {
public static function escapeLike($str) {
return str_replace(['\', '%', '_'], ['\\', '\%', '\_'], $str);
}
}
I was hoping for something database-agnostic and more robust. I think you can change the escape char in MySQL, although I don't know why you would.
我希望有一些与数据库无关且更健壮的东西。我认为您可以更改 MySQL 中的转义字符,尽管我不知道您为什么要这样做。