问题
How can I escape a LIKE
clause in Laravel/Eloquent? e.g.,
$search = Input::query('sSearch', '');
if($search !== '') {
$paginatedBookings->where('first_name', 'LIKE', '%' . $search . '%');
}
If $search
contains a %
or _
they need to be escaped.
回答1:
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
);
}
回答2:
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);
}
}
reference
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.
来源:https://stackoverflow.com/questions/22749182/laravel-escape-like-clause