Jump to content

Ignore html and bbcode?


newbtophp

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.

Archived

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

×
×
  • 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.