The Little Guy Posted June 9, 2007 Share Posted June 9, 2007 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 More sharing options...
obsidian Posted June 9, 2007 Share Posted June 9, 2007 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); } ?> Link to comment https://forums.phpfreaks.com/topic/54834-bold-array-of-words-re/#findComment-271222 Share on other sites More sharing options...
The Little Guy Posted June 9, 2007 Author Share Posted June 9, 2007 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; } ?> Link to comment https://forums.phpfreaks.com/topic/54834-bold-array-of-words-re/#findComment-271223 Share on other sites More sharing options...
sKunKbad Posted June 9, 2007 Share Posted June 9, 2007 "|{$v}|i" I'm a regex newbie, can you please explain this one. Link to comment https://forums.phpfreaks.com/topic/54834-bold-array-of-words-re/#findComment-271246 Share on other sites More sharing options...
obsidian Posted June 9, 2007 Share Posted June 9, 2007 "|{$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 Link to comment https://forums.phpfreaks.com/topic/54834-bold-array-of-words-re/#findComment-271332 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.