phpphp-8

How to perform case insensitive str_contains?


I have plenty of if(mb_stripos($hay, $needle) !== false) in my code. How do I replace it with str_contains()?

For example, I have this helper function in my code:

<?php

function str_contains_old(string $hay, string $needle): bool
{
    return mb_stripos($hay, $needle) !== false;
}

$str1 = 'Hello world!';
$str2 = 'hello';
var_dump(str_contains_old($str1, $str2)); // gives bool(true)

$str1 = 'Część';
$str2 = 'cZĘŚĆ';
var_dump(str_contains_old($str1, $str2)); // gives bool(true)

$str1 = 'Część';
$str2 = 'czesc';
var_dump(str_contains_old($str1, $str2)); // gives bool(false)

How to make it work with new str_contains()?

var_dump(str_contains('Hello world!', 'hello')); // gives bool(false)

Demo


Solution

  • You want a case-insensitive version of str_contains() The short answer is: There isn't one.

    The long answer is: case-sensitivity is encoding and locale dependent. By the time you've added those are information to a hypothetical str_icontains(), you've recreated mb_stripos(). TL;DR - Don't do it.