Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search in words on an string and change formatting

Tags:

php

search

I wan't to create a highlight tag search function via php

when I search a part of word...whole of word be colored

for example this is a sample text:

Text: British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor.

when I search "th" the output be like this:

Text: British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor.

So...I tried this code...please help me to complete it.

This is a 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 it in php language?

like image 509
user2726957 Avatar asked Mar 18 '23 22:03

user2726957


2 Answers

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

Usage:

$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

Edit after your comment:

...How can I do it for middle characters? for example "line"

Very easy, just update the regex pattern accordingly

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

Fiddle

like image 75
Hanky Panky Avatar answered Mar 26 '23 01:03

Hanky Panky


Use strpos() to find the position of the character you search for.. Then start reading from that identified position of character to till you don't find any space..

like image 20
malar Avatar answered Mar 26 '23 02:03

malar