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

后端 未结 2 1100
借酒劲吻你
借酒劲吻你 2021-01-25 18:36

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

2条回答
  •  春和景丽
    2021-01-25 18:42

    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

提交回复
热议问题