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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:17:17  来源:igfitidea点击:

Laravel: Escape "LIKE" clause?

phplaravellaravel-4

提问by mpen

How can I escape a LIKEclause in Laravel/Eloquent? e.g.,

如何LIKE在 Laravel/Eloquent 中逃避条款?例如,

$search = Input::query('sSearch', '');
if($search !== '') {
    $paginatedBookings->where('first_name', 'LIKE', '%' . $search . '%');
}

If $searchcontains 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);
    }
}

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.

我希望有一些与数据库无关且更健壮的东西。我认为您可以更改 MySQL 中的转义字符,尽管我不知道您为什么要这样做。