1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PHPの文字列検索でSQLの”LIKE”的に使える関数を作ってみた

Last updated at Posted at 2022-03-21

コピペ用関数

こちらをコピーして使ってください。

functions.php
function strlike(string $haystack, string $needle): bool
{
    //
    $initial_is_percent = false;
    $final_is_percent = false;

    //
    if (substr($needle, 0, 1) === '%') {
        $initial_is_percent = true;
    } else {
        //no action.
    }

    //
    if (substr($needle, -1) === '%') {
        $final_is_percent = true;
    } else {
        //no action.
    }

    //
    $matched = false;
    if (
        $initial_is_percent === true &&
        $final_is_percent === true
    ) { //部分一致!
        $needle = substr($needle, 1); //最初の%を切る
        $needle = substr($needle, 0, -1); //最後の%を切る
        if (str_contains($haystack, $needle) === true) {
            $matched = true;
        } else {
            //no action.
        }
    } else if (
        $initial_is_percent === false &&
        $final_is_percent === true
    ) { //前方一致!
        $needle = substr($needle, 0, -1); //最後の%を切る
        if (str_starts_with($haystack, $needle) === true) {
            $matched = true;
        } else {
            //no action.
        }
    } else if (
        $initial_is_percent === true &&
        $final_is_percent === false
    ) { //後方一致!
        $needle = substr($needle, 1); //最初の%を切る
        if (str_ends_with($haystack, $needle) === true) {
            $matched = true;
        } else {
            //no action.
        }
    } else {
        if ($needle === $haystack) {
            $matched = true;
        } else {
            //no action.
        }
    }

    return $matched;
}

使い方

LIKE句のように「%」を組み合わせることで部分一致や前方一致が確認できます。

//部分一致
strlike('abcdefg', '%cde%'); // -> true
strlike('abcdefg', '%ce%'); // -> false

//前方一致
strlike('abcdefg', 'abc%'); // -> true
strlike('abcdefg', '%abc'); // -> false

//後方一致
strlike('abcdefg', '%efg'); // -> true
strlike('abcdefg', 'defg%'); // -> false

//完全一致
strlike('abcdefg', 'abcdefg'); // -> true
strlike('abcdefg', 'abcd'); // -> false
1
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?