Friday, May 10, 2013

Highlight a portion of string

Highlight portion of word or whole word



<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   </head>
   <body>
      <div id="wrap">
<?php
// haystack
$text   = '<p>sending packages to travel agents</p>';
$text = strip_tags($text);

// search terms
$search = array(
    'age',
    'ing'
);

// print highlighted string
echo highlight($text, $search);

function highlight($haystack, $search)
{
$colors       = array(
    'FFFF00',
    'FF9900',
    'FF0000',
    'FF00FF',
    '99FF33',
    '33FFCC',
    'FF99FF',
    '00CC33'
);
    $tmp = array();
    foreach ($search as $key => $value) {
        $haystack = preg_replace("/($value)/i", "<span class='pop' style='background:#".$colors[$key].";font-weight:bold;'>\${1}</span>", $haystack, -1,$count);
  echo "<p>Word <span style='background:#{$colors[$key]};font-weight:bold;'>$value</span> found ".$count." time(s)</p>";
  $tmp[$key] = $count;
    }
 
    return "<p>".$haystack."</p>"."<p>Got total ".array_sum($tmp)." hit(s).</p>";
}
?>   
            <div>
   </body>
</html>

No comments:

Post a Comment