php 如何使 strpos 不区分大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6795383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:16:19  来源:igfitidea点击:

How to make strpos case insensitive

phpstrpos

提问by EnexoOnoma

How can I change the strpos to make it non case sensitive. The reason is if the product->nameis MadBikeand the search term is bikeit will not echo me the link. My main concern is the speed of the code.

如何更改 strpos 以使其不区分大小写。原因是如果product->nameMadBike并且搜索词是自行车,它不会回显链接。我主要关心的是代码的速度。

<?php
$xml  = simplexml_load_file('test.xml');
$searchterm = "bike";
foreach ($xml->product as $product) {
if (strpos($product->name, $searchterm) !== false ) {
echo $product->link;
} }
?>

回答by Dereleased

You're looking for stripos()

您正在寻找 stripos()

If that isn't available to you, then just call strtolower()on both strings first.

如果这对您不可用,那么只需先调用strtolower()两个字符串。

EDIT:

编辑

stripos()won't work if you want to find a substring with diacritical sign.

stripos()如果您想找到带有变音符号的子字符串,则不起作用。

For example:

例如:

stripos("Le?y Jerzy na wie?y i nie wierzy, ?e na wie?y le?y du?o JE?Y","je?y");returns false, but it should return int(68).

stripos("Le?y Jerzy na wie?y i nie wierzy, ?e na wie?y le?y du?o JE?Y","je?y");返回false,但它应该返回int(68)

回答by Turnsole

回答by KDawg

'i'in stripos()means case insensitive

的“i”stripos函数()是指不区分大小写

if(stripos($product->name, $searchterm) !== false){ //'i' case insensitive
        echo "Match = ".$product->link."<br />;
    }

回答by user1483887

make both name & $searchterm lowercase prior to $strpos.

在 $strpos 之前将 name 和 $searchterm 设为小写。

$haystack = strtolower($product->name);
$needle = strtolower($searchterm);

if(strpos($haystack, $needle) !== false){  
    echo "Match = ".$product->link."<br />;
}