0

I have a varying number of strings (album titles from mp3s), but some of them are over 20 characters long. They have spaces in them. I want to be able to find the long ones, and the most central space, and insert a line break in there.

How can I do this in PHP?

Chud37
  • 4,907
  • 13
  • 64
  • 116
  • you must assign some limits for example: all spaces greater than 10 then line break... –  Feb 11 '13 at 15:43
  • 2
    Please post your code of what you've tried. – War10ck Feb 11 '13 at 15:43
  • See http://stackoverflow.com/questions/9815040/smarter-word-wrap-in-php-for-long-words for wordwrap() or http://stackoverflow.com/questions/363425/how-to-wrap-long-lines-without-spaces-in-html for CSS. – mario Feb 11 '13 at 15:44
  • I havent tried anything yet. I could write a long foreach that would scan for every string over 20 and then find the closest space, but it would be too drawn out and I want a smooth quick function to do it. – Chud37 Feb 11 '13 at 15:45

2 Answers2

2

You need to use the wordwrap function. See the docs at php.net

$longString = "This is a really really long string that exceeds 20 characters";
$longString = wordwrap($longString, 20, "\n"); // or use <br/>
Kami
  • 19,134
  • 4
  • 51
  • 63
1
$arr = array();
$arr = explode(" ", $string);
$display_string = "";

foreach($arr AS $word){
 $length = strlen($display_string) + strlen($word);
 if($length >= 20){
  $display_string .= "<br />".$word." ";
 }else{
  $display_string .= $word." ";
 } 
}
echo $display_string;