RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

Return Search Snippet With Keyword Text

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
    if (!$match = trim($match)) continue;
12
    $snippet .= (isset($snippet)) ? $match . '...' : '... ' . $match . '... ';
13
  }
14
 
15
  $snippet = preg_replace("#($keyword)#i", '<strong>$1</strong>', $snippet);
16
 
17
 return $snippet;
18
}
19
 
20
/* Usage */
21
echo beliefmedia_search_snippet($keyword, $text);

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment