Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Romain's avatar
Level 30

Str::contains case insensitive

Hey there,

I guess it's in the question. Is there a way to use Str::contains() in a case-insensitive manner? Actually I kinda know the answer as the method uses mb_strpos under the hood and that's case-sensitive.

Using mb_stripos would make it possible, but is that a change that I should propose to the framework? It would be a breaking change so...

I could also "simply" force all my strings to be lower/uppercase and check after that, but it feels like overhead that shouldn't be required.

Thanks for any help

0 likes
8 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Just add your own

Str::macro('containsInsensitive', function($haystack, $needles)
    {
        foreach ((array) $needles as $needle) {
            if ($needle !== '' && mb_stripos($haystack, $needle) !== false) {
                return true;
            }
        }

        return false;
    }
3 likes
Romain's avatar
Level 30

@Sinnbeck I like this idea. But gotta say that if @tippin 's PR gets through it would be much better :D

I'll wait to see if it gets merged. So the best answer will be: $best = $merged ? Tippin : Sinnbeck; :D

Tippin's avatar

@Romain Well it was closed for now haha. Seems it breaks something further back, so they asked I PR it on master, so I suppose L9.x.

Romain's avatar
Level 30

hmm that's cool. But isn't v9 expected to be released in March next year? That's a bit far for me :D I guess for now I will go with @sinnbeck's solution and set a reminder to switch when L9 gets out.

Thank you both.

Tippin's avatar

@romain You made me realize I could use this caseless flag myself, as some projects I work on will often just lowercase the string before using Str::contains().

@sinnbeck solution would work plenty fine, but seeing how Str::remove() has a case-sensitivity flag, I went ahead and put in a pull request for this:

https://github.com/laravel/framework/pull/39083

So perhaps we can soon have it built in 😇

2 likes
Romain's avatar
Level 30

@Tippin Well thanks a lot for that, that was my next move actually. Let's hope it gets merged.

I've had to have both cases every time so far and it was getting annoying:

Str::contains($this->name, ['Complete', 'COMPLETE', 'END', 'end']);

Some of the arrays would soon require their own JSON file with all the combinations :D

Please or to participate in this conversation.