55

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;
} }
?>
Tiberiu-Ionuț Stan
  • 5,033
  • 5
  • 34
  • 61
EnexoOnoma
  • 7,471
  • 16
  • 82
  • 166

4 Answers4

112

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

Ethan
  • 4,165
  • 4
  • 22
  • 41
Dereleased
  • 9,427
  • 3
  • 32
  • 48
  • 5
    No, but it is slightly faster than using `strtolower()` first; on average, it (`stripos`) seems to take about 2.5 times longer (than `strpos`). Then again, you can still do it (`stripos`) a million times per second, so I wouldn't worry that much about it -- premature optimization is the root of all evil. – Dereleased Jul 22 '11 at 20:01
  • In theory, no solution can be, because there are more comparisons to be made. But here is some data: http://lzone.de/articles/php-string-search.htm – Turnsole Jul 22 '11 at 20:02
  • It's true, and my figures are based on searching short strings (the million times a second comment); obviously, the longer the string, the longer it takes, and even longer for stripos. However, in this question it seems like the strings will generally be short. – Dereleased Jul 22 '11 at 20:06
  • For example, if I increase the size of my search string by an order of magnitude, stripos goes from taking 0.2 seconds for 200,000 searches to taking 0.9 seconds; strpos, however, goes from 0.08 to 0.11 – Dereleased Jul 22 '11 at 20:07
  • So its not a difference, as you said premature optimization. Is stripos faster than preg_match right? – EnexoOnoma Jul 22 '11 at 20:11
12

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

stripos() is not case-sensitive.

Turnsole
  • 3,282
  • 4
  • 26
  • 50
1

'i' in stripos() means case insensitive

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

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 />;
}