Page 1 of 1
Display text around a given keyword
Posted: Tue May 03, 2005 8:28 am
by bytte
I'm building a PHP/MYSQL search on my website.
I'm using the mysql match()against() query to find keywords in my database.
That works fine. Now I'm using substr() to display part of the text of an item that's in the database. That works ok but it would be really nice to show the text AROUND the keyword(s) the user was looking for.
You know what I mean, it's the thing Google uses as well.
Can that be done in PHP?
Basically it needs to find the word in a text in the database, then return a few words before and after that word.
Posted: Tue May 03, 2005 10:57 am
by Skara
Get the location of the first letter of the word then - and + the indexes.
In other words,
Code: Select all
$string = "a bit of text to search through as an example";
// search for the word "search"
// get the index of the 's', which is 17
$start = $search_index - 10;
$end = $search_index + 10;
print(substr($string,$start,$end));
I think I got that right. >.>
That make sense?
...
Posted: Tue May 03, 2005 1:00 pm
by Calimero
Just to add:
When taking the "end" coordinate - use
$end = $search_index + 10 + length_of_the_keyword;
Posted: Tue May 03, 2005 1:08 pm
by timvw
or if multiple keywords where used... could would look like (untested)
Code: Select all
$keywords = array('fries', 'burger', 'kebab');
$replacements = '<b>\1</b>';
$result = mysql_query(...);
while ($row = mysql_fetch_assoc($result))
{
$row['text'] = preg_replace($keywords, $replacement, $row['text']);
echo $row['text'];
}
Posted: Tue May 03, 2005 1:29 pm
by bytte
Awesome. Thanks a lot.
Posted: Wed May 04, 2005 3:42 am
by bytte
What would be the best way to get the keywords in an array?
I mean, I can look for spaces, but what if the user inputs its search terms like this:
fries,burger,coca-cola
or like
fries, burger, coca cola
or even worse, in boolean mode
fries-burger
or fries+burger
or "burger king"
Posted: Wed May 04, 2005 5:12 am
by timvw
I thought you had already separated those words, because how would you feed them otherwise to mysql for the fulltext search?? Anyway, meaby you can ask McGruff where his search_engine code is (Apparently it has moved...)
Posted: Wed May 04, 2005 6:04 am
by bytte
I found it to be safe to send the string to mysql using the
Code: Select all
mysql_real_escape_string($keywords)
function. Mysql perfectly does the rest.