I have a div which has a fluid width, thus I cannot predict its size in PHP. If someone enters a long string which isn\'t delimited by spaces anywhere, the browser will stretch
There is a CSS property of:
word-wrap: break-word;
Otherwise if you want to keep this PHP, Idealy you only want to apply a break on words with character counts greater than X, This will split the string on the space and apply a check to each word. You may run into problems with links, but you could easily check for starting url characters or apply a regex.
$text = 'this text is fine but waaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaay long stuff gets broken waaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaay up into bits';
if($array = explode(' ',$text) and is_array($array))
{
foreach($array as $key => $value)
{
if(strlen($value) > 10)
$array[$key] = wordwrap($value, 10, "", true);
}
$text = implode(' ',$array);
}
echo $text;
In this example words with a length greater than 10 are then word wrapped with the character, which is pretty useful as it produces a soft hyphen on breaks. Replace it with your breaking character if you would perfer no additional hyphens. You can also try the word wrap with a lower number than the max length before breaking, IE strlen > 20, word wrap at 10
Sample: http://i.imgur.com/fKINR.png