Search in words by line and format changes

I don't want to create a shortcut search function via php

when I search for a part of a word ... the whole word will be colored

for example, this is an example of text:

Text: UK regulators say traders used private online chats to coordinate their purchases and sales in order to change currency prices in their favor.

when I search for "th", the result will be like this:

Text: UK regulators say traders used private online chats to coordinate their buying and selling, to change the currency prices in them .

So ... I tried this code ... please help me fill it out.

This is the algorithm:

$text= "British regulators say...";
foreach($word in $text)
{
  if( IS There "th" in $word)
   {
      $word2= '<b>'.$word.'</b>'
      replace($word with word2 and save in $text) 
   }
}

how can i do this in php language?

+4
5
function highLightWords($string,$find)
{
   return preg_replace('/\b('.$find.'\w+)\b/', "<b>$1</b>", $string); 
}

:

$string="British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor.";
$find="th";
print_r(highLightWords($string,$find));

Fiddle

:

... ? , ""

,

return preg_replace("/\b(\w*$find\w*)\b/", "<b>$1</b>", $string); 

Fiddle

+2

strpos(), , . , - .

+2

:

$word = "th";
$text = preg_replace("/\b($word.*?)\b/", "<b>$1</b>", $text);
+1

.

-, , php - , , ajax...

, , Javascript .

, , , , :

- :

$str = "Hello world. It a beautiful day.";
$words = explode(" ",$str);

Words var .

(), .

+1

You can go with the following code

   <?php

    $string = "British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor";

     $keyword = "th";
     echo highlightkeyword($string , $keyword );

    function highlightkeyword($str, $search) {
        $occurrences = substr_count(strtolower($str), strtolower($search));
        $newstring = $str;
        $match = array();

        for ($i=1;$i<$occurrences;$i++) {
            $match[$i] = stripos($str, $search, $i);
            $match[$i] = substr($str, $match[$i], strlen($search));
            $newstring = str_replace($match[$i], '[#]'.$match[$i].'[@]', strip_tags($newstring));
        }

        $newstring = str_replace('[#]', '<b>', $newstring);
        $newstring = str_replace('[@]', '</b>', $newstring);
        return $newstring;

    }

    ?>

Check out https://eval.in/220395

+1
source

All Articles