How to use wordwrap or otherwise to break text to fit a fluid-width div

依然范特西╮ 提交于 2019-12-02 03:13:11

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

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,​ Stackoverf​low! 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>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!