vishal kumar vishal kumar - 2 years ago 81
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
contains the search string.
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) {
$highlight[] = $find;

} else {
$highlight[] = $find;


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>";
return $str;


But when i put this into an array and when i print this array
. It given me this


[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):-


$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


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