Jump to content

Archived

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

pauldekrey

Bold a certain number of words in a dynamic string

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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...

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites

×

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.