61

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

4 Answers 4

128

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

5
  • 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, 2011 at 20:01
  • In theory, no solution can be, because there are more comparisons to be made. But here is some data: lzone.de/articles/php-string-search.htm
    – Turnsole
    Jul 22, 2011 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, 2011 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, 2011 at 20:07
  • So its not a difference, as you said premature optimization. Is stripos faster than preg_match right?
    – EnexoOnoma
    Jul 22, 2011 at 20:11
14

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

stripos() is not case-sensitive.

2
  • Dereleased's comment didn't show up before I hit enter. Post ninja'd!
    – Turnsole
    Jul 22, 2011 at 20:00
  • 2
    I blame the internet pixies, blocking the tubes with stale server-dust.
    – Turnsole
    Jul 23, 2011 at 21:01
3

'i' in stripos() means case insensitive

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.