tags:

views:

1172

answers:

2

Im 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 ??

Any help appreciated!

$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???

Apologies for the vagueness of the original question.

Donal

+9  A: 

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';
}
?>
Dominic Rodger
Good to know :)I have always been doing strtolower($var1) == strtolower($var2) to do case insensitive comparison
aip.cd.aish
Exactly how I'd do it. For regular string comparison I always use it's case sensitive brother 'strcmp' you can never be too careful with PHP's loose typing.
Phil Carter
Depending on what you are comparing you might want to add a trim to clear trailing whitespace. if(strcasecmp(trim($var1), trim($var2)) == 0) {}
Ryan Schumacher
If you are going to do strtolower method, use strcmp(mb_strtolower($var1), mb_strtolower($var2)) to take in consideration multi-byte strings.
Ryan Schumacher
+1  A: 

strcasecmp

Mitja