Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore case sensitivity when comparing strings in PHP

Tags:

php

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?

like image 264
Donal.Lynch.Msc Avatar asked Oct 30 '09 16:10

Donal.Lynch.Msc


People also ask

Does == case-sensitive?

Yes, == is case sensitive.

Is Strcmp case-sensitive in PHP?

The strcasecmp() function is a built-in function in PHP and is used to compare two given strings. It is case-insensitive. This function is similar to strncasecmp(), the only difference is that the strncasecmp() provides the provision to specify the number of characters to be used from each string for the comparison.

How do you make string comparison not case-sensitive?

The most basic way to do case insensitive string comparison in JavaScript is using either the toLowerCase() or toUpperCase() method to make sure both strings are either all lowercase or all uppercase.


2 Answers

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'; } ?> 
like image 75
Dominic Rodger Avatar answered Sep 30 '22 05:09

Dominic Rodger


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 } 
like image 37
Tim Visée Avatar answered Sep 30 '22 05:09

Tim Visée