Ignore case sensitivity when comparing strings in PHP

php

Question

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 = array( "hat","Cat","sAt","maT" );
// for each element in $arr_query_words -
for( $j= 0; $j < count( $arr_query_words ); $j++ ){

    // Split the $query_string on "_" or "%" :
    $story_body = str_replace( $arr_query_words[ $j ],
         '<span style=" background-color:yellow; ">' . $arr_query_words[ $j ] . '</span>',
               $story_body );

// --- This ONLY replaces where the case [upper or lower] is identical ->
}

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

1
45
1/5/2015 2:38:19 PM

Accepted Answer

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';
}
?>
77
10/30/2009 5:00:58 PM

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
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon