Ignore case sensitivity when comparing strings in PHP

I am trying to compare words for equality, and the case [upper and lower] does not matter. However, PHP does not seem to agree! Any ideas on how to get PHP to ignore the case of words when 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 do a replacement, even if the case is different?

+45
php
Oct 30 '09 at 16:22
source share
6 answers

Use str_ireplace to perform str_ireplace string replacement ( str_ireplace is available with PHP 5):

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

For random string comparisons, use strcasecmp :

 <?php $var1 = "Hello"; $var2 = "hello"; if (strcasecmp($var1, $var2) == 0) { echo '$var1 is equal to $var2 in a case-insensitive string comparison'; } ?> 
+78
Oct 30 '09 at 16:25
source share
β€” -

The easiest and most widely supported way to achieve this is perhaps the lowercase letters of both lines before comparing them, like so:

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

You might want to trim the lines to be compared, just use something similar to achieve this functionality:

 if(strtolower(trim($var1)) == strtolower(trim($var2))) { // Equals, case ignored and values trimmed } 
+23
Mar 06 '13 at 17:46
source share
+5
Oct 30 '09 at 16:25
source share
 $var1 = "THIS is A teST"; $var2 = "this is a tesT"; if (strtolower($var1) === strtolower($var2) ) { echo "var1 and var2 are same"; } 

strtolower converts a string to lowercase

+4
Nov 06. '13 at 4:33
source share
 if(!strcasecmp($str1, $str2)) ... //they are equals ignoring case 

strcasecmp returns 0 only if the lines are equal, ignoring case, therefore! strcasecmp returns true if they are equal, ignoring case, otherwise false

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

+2
Apr 20 '17 at 10:18
source share

I always add the ascii difference between uppercase and lowercase in lowercase characters.

-2
Sep 16 '14 at 16:05
source share



All Articles