Jump to content

Bold array of words re.


The Little Guy

Recommended Posts

OK... I posted a topic about bolding words earlier, but it works 50%,

 

This works, but it is case sensitive

<?php
function boldText($string, $array){
foreach($array as $replace){
	$string = str_replace($replace,'<strong>'.$replace.'</strong>',$string);
}
return $string;
}
?>

 

This works on everything, but it lowercases letters that are supposed to be uppercase

<?php
function boldText($string, $array){
foreach($array as $replace){
	$string = str_ireplace($replace,'<strong>'.$replace.'</strong>',$string);
}
return $string;
}
?>

 

So... If you haven't figured out my question, how do I make these words bold without changing their case?

Link to comment
https://forums.phpfreaks.com/topic/54834-bold-array-of-words-re/
Share on other sites

Try this:

<?php
function boldText($string, $array) {
  $replace = array();
  foreach ($array as $k => $v) {
    $array[$k] = "|{$v}|i"; // make regexp match for it
    $replace[] = "<strong>{$v}</strong>";
  }

  return preg_replace($array, $replace, $string);
}
?>

 

You may even be able to get by with this a little simpler:

<?php
function boldText($string, $array) {
  foreach ($array as $k => $v) {
    $array[$k] = "|({$v})|i"; // make regexp match for it
  }

  return preg_replace($array, '<strong>$1</strong>', $string);
}
?>

"|{$v}|i"

 

I'm a regex newbie, can you please explain this one.

 

Here's the breakdown. Remember that since it's in a string instead of directly in the regular expression, we're parsing out the variable within our loop:

|  = opening delimiter
{  = set off our variable within the string
$v = the variable which we wish to be included in the match (the VALUE of the variable)
}  = set off our variable within the string
|  = closing delimiter
i  = declare match as case insensitive

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.