5

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Considering thats not out yet (looks like it even got pulled from the php manual site??) .... its behavior may change by the time its implemented. Last I read "there is no case insensitive variant". – IncredibleHat Jul 27 '20 at 18:59
  • 2
    Worst case scenario here, is you either continue using the stripos as we have been doing for decades... or wrap the inputs in `strtolower()` so its comparing two identical case'd strings :( Both equally as ugly. – IncredibleHat Jul 27 '20 at 19:10
  • It may be added in the future: "Concerning the case-insensitivity for this function: This might be a feature for the future" – Jsowa Sep 25 '20 at 22:23
  • 2
    Yes, Stack Overflow, this is a released function as of PHP8 https://www.php.net/manual/en/function.str-contains.php – mickmackusa Aug 01 '21 at 08:38

2 Answers2

15

Just convert both string and haystack to lowercase beforehand

$string = strtolower($originalString);
$haystack = strtolower($originalHaystack);
$isMatched = str_contains($originalHaystack,$originalString);
14

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.

NikiC
  • 100,734
  • 37
  • 191
  • 225
Sara
  • 719
  • 5
  • 8