Jump to content

Recommended Posts

I've created a function to limit the amount of text according to the amount of words.

 

However it ruins html and bbcode tags.. :(. I only want it to have affect on everything else within $text but not bbcode & html.

 

Heres the code:

<?php

function containText($text, $length) {

        $words= explode(' ', $text); // string to array
    foreach ($words as $word) {
        $break = 0;
        for ($i = 0; $i < strlen($word); $i++) {
            if ($break >= $length) {
                $word= wordwrap($word, $length, '-<br>', true); //add <br> every $length chars
                $break = 0;
            }
            $break++;

        }
        $newText[] = $word; //add word to array
    }
    $text = implode(' ', $newText); //array to string
    
    $text = wordwrap($text, $length, "<br />\n");
    return $text;
}


$text = "PHPfreaks is awesome!!!!!
Lets Party! [img=http://awesome.gif]
<img src=\"image.gif\"> Yay!
<a href=\"http://www.phpfreaks.com\">Woot</a>
[font=2]BIG![/font]";


print containText($text, 10);

?>

 

:-\

Link to comment
https://forums.phpfreaks.com/topic/192562-ignore-html-and-bbcode/
Share on other sites

This is a common problem when wishing to use a summarised text for list display purposes.

 

As you have no way of knowing when your truncation is going to come smack in the middle of some markup, then the only practical solution is to strip the markup and display the summary text without any internal markup.

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.