0

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;
}
2
  • Beware using this approach if the source data is likely to contain any HTML or indeed URLs, etc. (e.g.: What happens in the word "obama" is in a URL.) Commented Dec 22, 2010 at 18:47
  • I take the $result from a string that is only a short description that doesn't contain any html neither is a url. the thing is i need to put it bold even if the string has caps letters Commented Dec 22, 2010 at 19:04

4 Answers 4

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

or use a regex with case insensitive.

Sign up to request clarification or add additional context in comments.

1 Comment

str_replace doesn't work because if the keyword is in lowercaps and the result obama is in higuer caps it wouldnt replace it.
0
<?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

3 Comments

that didnt work :/ it removed all text and left only $string in bold.
works fine for me. echo boldText('US President Barack Obama on Wednesday signed a landmark law',array('Obama'));
i finally got it from the same website you told me, but there was another code at the end of the page.. So thank you :)
0

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.

1 Comment

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.