vishal kumar vishal kumar - 1 year ago 42
PHP Question

Highlighting strings with different orders in PHP

I am trying to highlight the strings. Whether they are in the sequence or not.
Like this -

$str = "star 5 hotel";
$keywords = "5 star hotels";


There is my function. It only highlights the last matching string.Here
$str
contains the search string.
$keyword
contains that string which i have stored into database

How can i highlight each matching string.

function highlight($str, $keyword) {

$str = "star hotel 5";
$keyword = "5 star hotel";

foreach($look as $find){
if(strpos($keyword, $find) !== false) {
if(!isset($highlight)){
$highlight[] = $find;

} else {
if(!in_array($find,$highlight)){
$highlight[] = $find;

}
}
}
}



if(isset($highlight)){
foreach($highlight as $replace){
$str = str_ireplace($replace,'<b>'.$replace.'</b>',$keyword);
$stra[] = str_ireplace($replace,'<b>'.$replace.'</b>',$keyword);

echo "<pre>";
print_r ($stra);
echo "</pre>";
}
}
echo $str."<br>";
die();
return $str;

}


But when i put this into an array and when i print this array
$stra[]
. It given me this

Array
(


[0] => 5 star hotel

[1] => 5 star hotel

[2] => 5 star hotel


)

I can not find way to combine these.

Output : -If have that keyword which is searching . then this must be Highlighted..

5 star hotel

Answer Source

This is what I assumed:-

I assume that you want to search each word of the search sting in the given string and if and only if all the words found then make string in bold (complete string).

Then do like below (Explanation given in comments):-

<?php

$search = "star 5 hotel"; //search string
$string = "5 star hotels"; // string in which you want to search

function highlight($search, $string) {

  $new_search = array_unique(array_filter(explode(" " ,$search)));//explode search string
  $found_count = 0; //create a counter
  foreach($new_search as $find){ // iterate over search words array
     if(strpos($string, $find) !== false) { // if word found in the string
        $found_count +=1; // increase the counter
     }
  }
  if(count($new_search) == $found_count){ //check that all words found in the string
     $string = "<b>". $string ."</b>"; // if yes then make each word of the string bold
  }

  return $string; //return the newly modified string
}

echo highlight($search, $string); // echo newly modified string

Output:- https://eval.in/838325

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download