Page 1 of 1

wordwrap()

Posted: Tue Aug 30, 2005 12:14 pm
by sk8erh4x0r
Is there a way to wrap text even when it's one long string?

ex:
thisisastringoftextthatneedstobewordwrapped

Can wordwrap() be used to split that up or would i need to use something else?

Posted: Tue Aug 30, 2005 12:28 pm
by s.dot
wordwrap() will split the string where you tell it to, so it will wrap that.

Posted: Tue Aug 30, 2005 1:51 pm
by sk8erh4x0r
no it doesn't. It won't split one string into 2.

Posted: Tue Aug 30, 2005 2:34 pm
by raghavan20
'wordwrap()' wraps the string at a position specified and introduces a newline character and puts the remaining string behind it which will allow to display properly in HTML.
if property cut is set, the string is terminated at the 'x' position you specify.
I think this might be useful when you want to provide headlines of some XML news feeds.

alright, lets assume a string is of 200 characters, you specify the wrap position at 70, so it puts a '<br />' at 70th position but the remaining string is longer than 70chars. wot it will do now???
Oh...I did not look at the other example, it wraps at every 70th position....good function...badly needed for overflowing div content.

Posted: Tue Aug 30, 2005 7:59 pm
by Chris Corbyn

Code: Select all

/*
 Wraps text at the given length of characters without splitting words
 -- in bits (unless it really needs to).
 */

function wrap_text($text, $length, $end='<br />')
{
    $tokens = preg_split('/\b/', $text); //Tokenize the string (maybe strtok() is better for this?)
    $temp = array();
    $out = '';
    $tmp = '';
    foreach ($tokens as $tok)
    {
        if (strlen($tmp.$tok) <= $length)
        {
            $tmp .= $tok;
        }
        elseif (strlen($tok) > $length) //The single word is too long => split it!
        {
            $out .= !empty($tmp) ? $tmp.$end : ''; //Build onto string
            $tmp = ''; //Reset tmp
            do
            {
                if (strlen($tok) > $length) $y = false;
                else $y = true;
                $out .= substr($tok, 0, $length).$end; //Build onto string
                $tok = substr($tok, $length); //Move along the token string
            } while (!$y); //End do..while
        }
        else
        {
            $out .= $tmp.$end; //Build onto string
            $tmp = ''; //Reset tmp
        } //End if
    } //End foreach

    return $out;
}
Seems to work... ;)