Jump to content

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);
}
?>

This works:

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.