Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make certain characters of a word from string bold

Tags:

regex

php

I need to highlight a certain characters from a string, I tried str_replace and preg_replace. But these work only if full word is entered,

$text = str_replace($searhPhrase, '<b>'.$searhPhrase.'</b>',  $text);
$text = preg_replace('/('. $searhPhrase .')/i', '<b>$1</b>', $text);

I want something like, if I search for 'and' even the letters from 'hand' should get highlighted.

Thanks in advance.

like image 722
Neha Dangui Avatar asked Jul 24 '15 09:07

Neha Dangui


1 Answers

$text = preg_replace('/\S*('. $searhPhrase .')\S*/i', '<b>$1</b>', $text);

This should do it for you.

or

if you want to highlight the whole word

$text = preg_replace('/(\S*'. $searhPhrase .'\S*)/i', '<b>$1</b>', $text);
like image 144
vks Avatar answered Sep 28 '22 11:09

vks