1

I have a PHP script that echo's a string into an html div.

The div has room for only 50 chars in width, so if the string is longer, I have to cut it in to how ever many lines it takes.

So I can use strlen to see where I should be cutting the string and echo a <br>. Problem is, I don't want to cut it in the middle of a word.

I had a solution in mind, but it seems that i'm over complicating this.

Thanks,

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Or Weinberger
  • 7,332
  • 23
  • 71
  • 116
  • http://stackoverflow.com/questions/717328/how-to-explode-string-right-to-left First you cut it, then you explode it by spaces and pop the last word off. – DanMan Mar 13 '11 at 10:26
  • You can use `textarea` as well and using CSS make it look like ordinary text: http://jsfiddle.net/dPnDp/ – Shadow The GPT Wizard Mar 13 '11 at 10:27

5 Answers5

8

Just add an attribute class="wrapping" to the div you want to have this behaviour, and add this css to your HTML page:

div.wrapping {
    word-wrap: break-word;
}
Luca Fagioli
  • 12,722
  • 5
  • 59
  • 57
0

http://www.totallyphp.co.uk/code/shorten_a_text_string.htm

You can use this simple function to shorten your text

Headshota
  • 21,021
  • 11
  • 61
  • 82
0

There are some examples in the PHP doc page for substr. Copy/pasting a couple:

$str = "aa bb ccc ddd ee fff gg hhh iii";
echo substr(($str=wordwrap($str,$len,'$$')),0,strpos($str,'$$'));

and

function _substr($str, $length, $minword = 3)
{
    $sub = '';
    $len = 0;

    foreach (explode(' ', $str) as $word)
    {
        $part = (($sub != '') ? ' ' : '') . $word;
        $sub .= $part;
        $len += strlen($part);

        if (strlen($word) > $minword && strlen($sub) >= $length)
        {
            break;
        }
    }

    return $sub . (($len < strlen($str)) ? '...' : '');
}
Jon
  • 428,835
  • 81
  • 738
  • 806
0

wordwrap($string, 50, "<br>\n")

aaz
  • 5,136
  • 22
  • 18
0

write function

// Original PHP code by Chirp Internet: www.chirp.com.au 
// Please acknowledge use of this code by including this header. 
function myTruncate($string, $limit, $break=".", $pad="...") { 
    // return with no change if string is shorter than $limit 
    if(strlen($string) <= $limit) return $string; 
       // is $break present between $limit and the end of the string? 
       if(false !== ($breakpoint = strpos($string, $break, $limit))) { 
           if($breakpoint < strlen($string) - 1) { 
                $string = substr($string, 0, $breakpoint) . $pad; 
           } 
       }
 return $string;
 }
Mohammad Efazati
  • 4,812
  • 2
  • 35
  • 50