用于强制表中换行符的PHP或HTML/CSS解决方案

Fra*_*isc 4 html css php line-breaks

我有一个表填充用户生成的文本.文本跨越TD允许的范围,但是如果输入是由长字符串组成的字符串而没有破坏字符(空格,破折号等),则会使表格变得混乱.

例如ggggggggggggggggggggggggggggggggggggggggggggggggggggggg

我怎样才能让它们包裹起来呢?

谢谢.

Bre*_*zer 9

你可以使用CSS:

table {
    table-layout: fixed;
    width: 100%;
}

table td, table th {
    word-wrap: break-word;       /* Internet Explorer 5.5+, Chrome, Firefox 3+ */
    overflow-wrap: break-word;   /* CSS3 standard: Chrome & Opera 2013+ */
}

/* Use this if you also want to preserve multiple spaces in text */
table td, table th {
    white-space: -moz-pre-wrap;  /* Firefox 1.0-2.0 */
    white-space: -pre-wrap;      /* Opera 4-6 */
    white-space: -o-pre-wrap;    /* Opera 7 */
    white-space: pre-wrap;       /* CSS3 */
}
Run Code Online (Sandbox Code Playgroud)

这是一个例子:http: //www.jsfiddle.net/QPP8A/ (现在已经过时了,抱歉)

如果您觉得难以应用,可以使用PHP的wordwrap函数:

$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");
Run Code Online (Sandbox Code Playgroud)

  • 你必须将父表的样式`table-layout`设置为值`fixed`以使其与`<td>一起使用 (2认同)