Ignore case sensitivity when comparing strings in PHP

Php

Php Problem Overview


I'm trying to compare words for equality, and the case [upper and lower] is irrelevant. However PHP does not seem to agree! Any ideas as to how to force PHP to ignore the case of words while comparing them?

$arr_query_words = ["hat","Cat","sAt","maT"];
for( $j= 0; $j < count($arr_query_words); $j++ ){
    $story_body = str_replace( 
        $arr_query_words[ $j ],
        '<span style=" background-color:yellow; ">' . $arr_query_words[ $j ] . '</span>',
        $story_body
   );
}

Is there a way to carry out the replace even if the case is different?

Php Solutions


Solution 1 - Php

Use str_ireplace to perform a case-insensitive string replacement (str_ireplace is available from PHP 5):

$story_body = str_ireplace($arr_query_words[$j],
   '<span style=" background-color:yellow; ">'. $arr_query_words[$j]. '</span>',
    $story_body);

To case-insensitively compare strings, use strcasecmp:

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
    echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?>

Solution 2 - Php

The easiest, and most widely supported way to achieve this is possibly to lowercase both strings before comparing them, like so:

if(strtolower($var1) == strtolower($var2)) {
    // Equals, case ignored
}

You might want to trim the strings being compared, simply use something like this to achieve this functionality:

if(strtolower(trim($var1)) == strtolower(trim($var2))) {
    // Equals, case ignored and values trimmed
}

Solution 3 - Php

$var1 = "THIS is A teST";
$var2 = "this is a tesT";
if (strtolower($var1) === strtolower($var2) ) {
    echo "var1 and var2 are same";
}

strtolower converts string to lowercase

Solution 4 - Php

if(!strcasecmp($str1, $str2)) ... //they are equals ignoring case

strcasecmp returns 0 only if strings are equals ignoring case, so !strcasecmp return true if they are equals ignoring case, false otherwise

http://php.net/manual/en/function.strcasecmp.php

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDonal.Lynch.MscView Question on Stackoverflow
Solution 1 - PhpDominic RodgerView Answer on Stackoverflow
Solution 2 - PhpTim ViséeView Answer on Stackoverflow
Solution 3 - PhpThusitha SumanadasaView Answer on Stackoverflow
Solution 4 - PhpLuca C.View Answer on Stackoverflow