Jump to content


Photo

Bold a certain number of words in a dynamic string


  • Please log in to reply
3 replies to this topic

#1 pauldekrey

pauldekrey
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 15 June 2006 - 08:16 PM

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: These are some words 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.



#2 litebearer

litebearer
  • Members
  • PipPipPip
  • Advanced Member
  • 2,357 posts
  • Locationwhite lake michigan

Posted 16 June 2006 - 12:36 AM

Might try...


<?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;
?>
Lite...

all the brothers were valiant!

[br][br]The truely intelligent people are not those who create the dots; rather they are they ones with the ability to connect the dots into a coherent picture

#3 pauldekrey

pauldekrey
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 16 June 2006 - 03:27 PM

Absolutely perfect!!! Thanks so much, litebearer!

#4 kanikilu

kanikilu
  • Members
  • PipPip
  • Member
  • 29 posts
  • LocationDallas, TX

Posted 16 June 2006 - 03:39 PM

Another possible solution:

$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);





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users