Peibol
Peibol

Reputation: 147

add html tags to a variable string

lets say

$keyword = obama
$result = "US President Barack Obama on Wednesday signed a landmark law"

How do i make that everytime $keyword appears inside $result it changes the $keyword to be inside <strong></strong> tags?

str_replace doesn't work because if the keyword is in lowercaps and the result obama is in higuer caps it wouldnt replace it.

Thanks

edit: found the answer, in case anyone needs it this is the code

$myWords = array($keyword);
function boldText($arrWords, $strSubject)
{
     if (!is_array($arrWords)) return;
     foreach ($arrWords as $strWord)
     {
          $strSubject = preg_replace('@(' . preg_quote($strWord, '@') . ')@i', "<b>\\1</b>", $strSubject);
     }
     return $strSubject;
}

Upvotes: 0

Views: 7416

Answers (4)

Mark Baijens
Mark Baijens

Reputation: 13222

str_replace (ucfirst($keyword), "<strong>" . $keyword . "</strong">, $result);

or use a regex with case insensitive.

Upvotes: 1

James Alday
James Alday

Reputation: 873

I'm sure there are probably other methods, but I'd use preg_replace(). Something like:

$result = preg_replace($keyword , "<strong>$keyword</strong>" , $result);

Upvotes: 0

Surreal Dreams
Surreal Dreams

Reputation: 26380

You can use str_replace:

str_replace ( mixed $keyword, mixed '<strong>' . $keyword . '</strong>', mixed $result)

This will replace the $keyword with itself, surrounded by <strong> tags.

Upvotes: 0

troynt
troynt

Reputation: 1912

<?php
function boldText($string, $array) {
  $string = strip_tags($string);
  return preg_replace('~('.implode('|', $array).'[a-zA-Z]{0,45})(?![^<]*[>])~is', '<strong>$0</strong>', $string );
}
?>

from http://php.bigresource.com/bold-string-from-array-of-keywords-HLRL2A8c.html

Upvotes: 0

Related Questions