PHP - 使用数据库搜索字符串LIKE语法/通配符(%,_)[重复]

This question already has an answer here:

I have an application receiving search requests using the syntax of a database LIKE notation (ex: %someth_ng%), but I must be able to apply this search not only to a database (which is straightforward), but to strings in my application, which is in PHP.

I'm thinking that using a regex is probably the best way to do this, but I'd like to see what solutions other people can/have come up with.

</div>

After a bit of work, this is the best I could come up with:

public function like($needle, $haystack)
{
    // Escape meta-characters from the string so that they don't gain special significance in the regex
    $needle = preg_quote($needle, '~');

    // Replace SQL wildcards with regex wildcards
    $needle = str_replace('%', '.*', $needle);
    $needle = str_replace('_', '.', $needle);

    // Add delimiters, modifiers and beginning + end of line
    $needle = '~^' . $needle . '$~isu';

    return (bool) preg_match($needle, $haystack);
}

I'm curious to see if there are any better solutions, or improvements to this one.