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.
Display text around a given keyword
Moderator: General Moderators
Get the location of the first letter of the word then - and + the indexes.
In other words,
I think I got that right. >.>
That make sense?
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));That make sense?
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'];
}I found it to be safe to send the string to mysql using the
function. Mysql perfectly does the rest.
Code: Select all
mysql_real_escape_string($keywords)