Using @Utkanos suggestion:
foreach($colors as $color) {
$output = $color['color_name'];
foreach(explode(' ', $_GET['keywords']) as $term)
$output = preg_replace('/('.$term.')(?![^>]*>)/i', '<strong>$1</strong>', $output);
echo $output .'<br />';
}
You want the result from the preg_match
to replace the $term
.
Sorry, it's a lot of code for a apparently "simply" problem, but this should do, what you expect:
$colors = array("Apple green",
"Banana yellow",
"Brick red",
"Charcoal",
"Coffee",
"Fire red");
$terms = "re e";
$output = "";
foreach($colors as $color) {
$output = $color;
$words = array();
foreach(explode(' ', $terms) as $term) {
$match = preg_match_all("/(". $term .")/i", $output, $hits, PREG_OFFSET_CAPTURE);
if($match) {
$positions = array();
foreach($hits[1] as $hit) {
for($i = $hit[1]; $i < strlen($hit[0]) + $hit[1]; $i++) {
$positions[] = $i;
}
$words[] = array($hits[0][0][0], $positions);
}
}
}
$positions = array();
foreach($words as $word) {
foreach($word[1] as $position)
$positions[] = $position;
}
$positions = array_unique($positions);
asort($positions);
$positions = array_values($positions);
if(count($positions) > 0) {
$offset = 0;
$open = false;
$closed = true;
$i = $positions[0];
foreach($positions as $value) {
if($value != $i AND !$closed) {
$output = substr_replace($output, "</strong>", $i + $offset, 0);
$offset += 9;
$open = false;
$closed = true;
$i = $value;
}
if(!$open AND $closed) {
$output = substr_replace($output, "<strong>", $value + $offset, 0);
$offset += 8;
$open = true;
$closed = false;
}
$i++;
}
if(!$closed)
$output = substr_replace($output, "</strong>", $positions[count($positions)-1] + $offset +1, 0);
}
echo $output ."<br/>";
}