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?
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
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With