When searching a block of text for a specific keyword, the following function will return each occurrence of a keyword with supporting contextual text. For example, consider the following block of text:
Bias is the tendency to have an opinion, or view, that is often without considering evidence and other information. Biases can be learned implicitly within cultural contexts. People may develop biases toward or against an individual, an ethnic group, a nation, a religion, a social class, a political party, theoretical paradigms and ideologies within academic domains, or a species. Biased means one-sided, lacking a neutral viewpoint, or not having an open mind. Bias can come in many forms and is related to prejudice and intuition. In science and engineering, a bias is a systematic error. Statistical bias results from an unfair sampling of a population, or from an estimation process that does not give accurate results on average.
When searching for the keyword of "bias", the following will be returned:
... Bias is the tendency... an open mind. Bias can come in...engineering, a bias is a systematic.... Statistical bias results from an...
PHP Function
1
<?php
2
/*
3
Return Search Snippet With Keyword Text
4
http://www.beliefmedia.com/code/php-snippets/search-snippet-text
5
*/
6
7
function beliefmedia_search_snippet($keyword, $text, $span = '15') {
8
9
preg_match_all("#(\W.{0,$span}\W)($keyword)(\W.{0,$span}\W)#i", " $text ", $matches);
10
foreach($matches[0] as $match) {
11
12
$snippet .= (isset($snippet)) ? $match . '...' : '... ' . $match . '... ';
13
}
14
15
16
17
return $snippet;
18
}
19
20
/* Usage */
21
echo beliefmedia_search_snippet($keyword, $text);