Web Hosting Talk







View Full Version : Use php to highlight a string?


lexington
05-03-2008, 04:21 AM
Hello, I was curious to know how I could use php to take some text from the database and if the text is a match it would surround it with bold html tags? For example if this text is stored in the DB:

one, two, three, four

If the keyword is two, it would output:

one, <b>two</b>, three, four

Remember that the text is static and all stored in the DB and pulled using one variable. I would assume that some explode and pregmatch commands are involved but could anyone provide me with a working example if it isn't too difficult? Thanks!

zinga
05-03-2008, 05:12 AM
If it's just one keyword, just use a str_replace, eg:


$text = str_replace('two', '<b>two</b>', $text);

You can even pass arrays in, eg:
$text = str_replace(array(
'one',
'two'
), array(
'<b>one</b>',
'<b>two</b>'
), $text);

Note that the above won't exactly replace words (ie, it would replace the word "hone" with "h<b>one</b>", but since you didn't specify you wanted words, I'm ignoring that).

If you think entering all the replacements into a str_replace is tedious, you can use a preg_replace, ie:
$text = preg_replace('/(one|two|three|four)/', '<b>$1</b>', $text);

lexington
05-03-2008, 05:17 AM
Oh duh I should have known that since I use str_replace all of the time but only for separate words. Thanks a lot I will try that and I may have to add additional code since I didn't mention that I will have it check to see if the user matches one of the keywords and if so then it will replace it.