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
This works for me:
<?
ini_set("display_errors", TRUE);
error_reporting(-1 ^ E_NOTICE);
header("Content-Type: text/html; charset=utf-8");
$line = "This is a test. Hello, Stackoverflow! This ought to trigger a couple of breaks";
$line = wordwrap($line, 10, "\n", true);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
<head>
<title>Linebreak Test</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<div style="white-space: pre"><?=$line?></div>
</body>
</html>
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