在PHP中比较字符串时忽略大小写 [英] Ignore case sensitivity when comparing strings in PHP
本文介绍了在PHP中比较字符串时忽略大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试比较单词的相等性,而大小写无关. 但是PHP似乎不同意!关于如何强迫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 = 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?
推荐答案
使用 str_ireplace
执行不区分大小写的字符串替换(PHP 5中提供了str_ireplace
):
$story_body = str_ireplace($arr_query_words[$j],
'<span style=" background-color:yellow; ">'. $arr_query_words[$j]. '</span>',
$story_body);
要以不区分大小写的方式比较字符串,请使用 strcasecmp
:
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';
}
?>
这篇关于在PHP中比较字符串时忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文