gpt4 book ai didi

php - 在 PHP 中比较字符串时忽略大小写敏感

转载 作者:IT王子 更新时间:2023-10-29 00:00:09 29 4
gpt4 key购买 nike

我正在尝试比较单词是否相等,大小写 [upper and lower] 无关紧要。然而PHP似乎并不同意!关于如何强制 PHP 在比较单词时忽略单词的大小写有什么想法吗?

$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
);
}

有没有办法在不同的情况下进行替换?

最佳答案

使用str_ireplace执行不区分大小写的字符串替换(str_ireplace 从 PHP 5 开始可用):

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

要不区分大小写地比较字符串,请使用 strcasecmp :

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?>

关于php - 在 PHP 中比较字符串时忽略大小写敏感,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1650864/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com