Laravel: Escape “LIKE” clause?

安稳与你 提交于 2019-12-10 02:38:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!