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?
JavaScript
x
$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?
Advertisement
Answer
Use str_ireplace
to perform a case-insensitive string replacement (str_ireplace
is available from PHP 5):
JavaScript
$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
:
JavaScript
<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?>