How to make strpos case insensitive
Asked Answered
S

4

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;
} }
?>
Sural answered 22/7, 2011 at 19:56 Comment(0)
M
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).

Metrify answered 22/7, 2011 at 19:58 Comment(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.Metrify
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.htmUnderdrawers
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.Metrify
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.11Metrify
So its not a difference, as you said premature optimization. Is stripos faster than preg_match right?Sural
U
14

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

stripos() is not case-sensitive.

Underdrawers answered 22/7, 2011 at 19:58 Comment(2)
Dereleased's comment didn't show up before I hit enter. Post ninja'd!Underdrawers
I blame the internet pixies, blocking the tubes with stale server-dust.Underdrawers
N
3

'i' in stripos() means case insensitive

if(stripos($product->name, $searchterm) !== false){ //'i' case insensitive
        echo "Match = ".$product->link."<br />;
    }
Nelson answered 28/3, 2013 at 22:44 Comment(0)
T
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 />;
}
Tubercular answered 8/1, 2016 at 13:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.