If you are looking for a php algorithm to rank search results based on proximity/relevance of multiple words here comes a quick and easy way of generating search results with PHP only:
Issues with the other boolean search methods such as
strpos()
, preg_match()
, strstr()
or stristr()
- can't search for multiple words
- results are unranked
PHP method based on Vector Space Model and tf-idf (term frequency–inverse document frequency):
It sounds difficult but is surprisingly easy.
If we want to search for multiple words in a string the core problem is how we assign a weight to each one of them?
If we could weight the terms in a string based on how representative they are of the string as a whole, we could order our res
ults by the ones that best match the query.
ults by the ones that best match the query.
On the performance side, use the strpos function. It is about three times faster and have in mind, when I did one million compares at once, it took preg match 1.5 seconds to finish and for strpos it took 0.5 seconds. What I'm trying to say is that it runs really fast either way.
if (strpos($a,'are') !== false) { echo 'true'; }
Note that the use of
!== false
is deliberate; strpos
returns either the offset at which the needle string begins in the haystack string, or the boolean false
if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are')
.
Another option is to use the strstr() function. Something like:
if (strlen(strstr($haystack,$needle))>0) { // Needle Found }
Point to note: The strstr() function is case-sensitive. For a case-insensitive search, use the stristr()function.
Not Using REGEXP:
Make use of case-insensitve matching using
stripos()
:if (stripos($string,$stringToSearch) !== false) { echo 'true'; }
strstr() function is case-sensitive. For a case-insensitive search, use the stristr()function.
String can be checked with the below function
function either_String_existor_not($str,$character){ if (strpos($str,$character) !== false) { return true; } else{ return false; } }---end---
Tags:
best coding
→
php regexp
Best function to check if string contains specific words?
By Game Changer →
Saturday, December 5, 2015