Jump to content

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.

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...
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]
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.