How to make strpos case insensitive

PhpStrpos

Php Problem Overview


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

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

Php Solutions


Solution 1 - Php

You're looking for stripos()

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

EDIT:

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

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).

Solution 2 - Php

http://www.php.net/manual/en/function.stripos.php

stripos() is not case-sensitive.

Solution 3 - Php

'i' in stripos() means case insensitive

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

Solution 4 - Php

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

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEnexoOnomaView Question on Stackoverflow
Solution 1 - PhpDereleasedView Answer on Stackoverflow
Solution 2 - PhpTurnsoleView Answer on Stackoverflow
Solution 3 - Phpuser1502852View Answer on Stackoverflow
Solution 4 - Phpuser1483887View Answer on Stackoverflow