PHP script/function to get 4-5 words around a keyword in a string(like google)
hey guys,
I am writing a search engine for a website. I was just wondering how i would write effecient/nice/clean PHP code for taking 4-5 words around a matched keyword in a string which contains the contents of a text file and then display the results in a similar fashion as google. I was thinking that this can be done with regexps but since i am no pro with them...i shout out to you guys to help me. Please suggest something. Thanks |
Something like this?
Code:
<? I was just wondering how i would write effecient |
This will work as well.
PHP Code:
|
Thank guys,
I will try both these peices of code firt thing in the mornign and let you know how it goes. I also wrote some code...but it is really ineffecient...i basically break up the string into an array at every space and then check each string with each search word(nested foreach loop....very ineffecient) and then print out the text around the amtched word. well newayz...now that u guys have given me this code...i can remove the one i have written and use either of these. thanks again. |
allright....i tested out the both the codes and the segment given by david_ross seems to work better for my needs.
However i was looking for a few enhancements in the code.As of now..the code only finds the first match in the tet, highlights it and prints it out. However i want to find all the matches and print them. This is kind of the thing google does too.It tends to find all the matches and then prints them out. Also if the search text provided by the user is more than one word, anothe rporblem arises.I changed the code given by david_ross to this: Code:
$search_arr = explode(" ",$search); I hope i have been able to explain my problem well and that someone will be able to help me. Thanks again. |
Quote:
thanks |
To find all matches, just use the g switch in the regex of david_ross code like :
PHP Code:
|
Quote:
I have this working right now...but the problem lies in the fact that this is taking too much time. It takes almost 8 seconds to display such a result with 2 hits only. I need to improve the time and even though a faster machine will change this significantly, I know i can definitely improve on my code too. so again...I call out for any help that is ready to come my way...:) sil vous plait. |
anyone...someone....if you are a reg exp guru...please help me out here.
|
All times are GMT -5. The time now is 04:57 AM. |