一个单词超过50个字符后自动空格键

时间:2013-12-31 18:56:42

标签: php

如果一个单词超过一定数量的字符,是否有一个可以自动添加spacer的函数?例如,给定一个包含100个字符的单词,它将在第50个字符处发布一个空格键。我正在创建一个评论系统,如果有人发布了类似的内容:

  

ASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDF

它会弄乱我的布局外观,因为单词中没有空格。

2 个答案:

答案 0 :(得分:4)

使用CSS而不是更改实际的单词/字符串:

div{
    display:table;
    word-break:break-all;
}

Demo

答案 1 :(得分:1)

要回答PHP,你可以使用像这样的函数(如果你真的需要):

<?php
$str = '1234567890123456789012345678901234567890123456789 123456789012345678901234567890123456789012345678901234567890 ASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDF';

function addSpace($str,$int){
 $output = '';
 $words = explode(' ', $str);
 foreach ($words as $word):
     $new = '';
     while(strlen($word)>$int){
     $new .= substr($word, 0, $int). ' ';
     $word = substr($word, $int);
     }
     $output .= "$new $word ";
 endforeach;
 return $output;
}
echo addSpace($str, 50);
?>