pauldekrey Posted June 15, 2006 Share Posted June 15, 2006 I am looking for a way to only bold the first few (for discussion's sake, let's say 4) words of a string being pulled from a database, ending up with an effect like this: [b]These are some words[/b] in my string.I expect that the easiest way to do this would be to count the number of spaces and echo a "</b>" before the 4th space. From the hunting I've done, it appears that ereg_replace() would probably do the trick, but I haven't found any usable examples, and I haven't been able to get a grasp of the syntax yet.Any help would be greatly appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/12098-bold-a-certain-number-of-words-in-a-dynamic-string/ Share on other sites More sharing options...
litebearer Posted June 16, 2006 Share Posted June 16, 2006 Might try...[code]<?PHP$contents="lots and lots of text and more and more";$max_words=4;$content_array = explode(" ",$contents);$count = count($content_array);if ($count> $max_words) { $i=0; for ($i=0;$i<$max_words;$i++) { $leading_text[$i] = array_shift($content_array); } $contents = implode(" ",$content_array); $bolded_text = '<B>' . implode(" ", $leading_text) . ' </b>' . $contents;}else{ $bolded_text = '<B>' . $contents . '</b>';}echo $bolded_text;?>[/code]Lite... Quote Link to comment https://forums.phpfreaks.com/topic/12098-bold-a-certain-number-of-words-in-a-dynamic-string/#findComment-46132 Share on other sites More sharing options...
pauldekrey Posted June 16, 2006 Author Share Posted June 16, 2006 Absolutely perfect!!! Thanks so much, litebearer! Quote Link to comment https://forums.phpfreaks.com/topic/12098-bold-a-certain-number-of-words-in-a-dynamic-string/#findComment-46300 Share on other sites More sharing options...
kanikilu Posted June 16, 2006 Share Posted June 16, 2006 Another possible solution:[code]$contents="lots and lots of text and more and more";$max_words=4;$contents_array = explode(' ', $contents);for ($i=0; $i<count($contents_array); $i++) { if ($i<$max_words) { $content[$i] = "<b>$contents_array[$i]</b>"; } else { $content[$i] = $contents_array[$i]; }}echo implode(' ', $content);[/code] Quote Link to comment https://forums.phpfreaks.com/topic/12098-bold-a-certain-number-of-words-in-a-dynamic-string/#findComment-46306 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.