php - 如何在 PHP 中插入自动换行功能来​​自动断开长单词?

标签 php html

如何插入自动换行功能,这样太长的单词就不会被截断 <div> border 但 line-returns 本身?

下面是我要自动换行的变量

$body = nl2br(addslashes($_POST['body']));

最佳答案

试试这些链接:

Smarter word-wrap in PHP for long words?

http://php.net/manual/en/function.wordwrap.php

http://www.w3schools.com/php/func_string_wordwrap.asp

还有一个自定义函数:

function smart_wordwrap($string, $width = 75, $break = "\n") {
// split on problem words over the line length
$pattern = sprintf('/([^ ]{%d,})/', $width);
$output = '';
$words = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY |     PREG_SPLIT_DELIM_CAPTURE);

foreach ($words as $word) {
    if (false !== strpos($word, ' ')) {
        // normal behaviour, rebuild the string
        $output .= $word;
    } else {
        // work out how many characters would be on the current line
        $wrapped = explode($break, wordwrap($output, $width, $break));
        $count = $width - (strlen(end($wrapped)) % $width);

        // fill the current line and add a break
        $output .= substr($word, 0, $count) . $break;

        // wrap any remaining characters from the problem word
        $output .= wordwrap(substr($word, $count), $width, $break, true);
    }
}

// wrap the final output
return wordwrap($output, $width, $break);
}

$string = 'hello! toolongheretoolonghereooheeeeeeeeeeeeeereisaverylongword but these words are     shorterrrrrrrrrrrrrrrrrrrr';
echo smart_wordwrap($string, 11) . "\n";

关于php - 如何在 PHP 中插入自动换行功能来​​自动断开长单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34080612/

相关文章:

javascript - 如何从form_dropdown中获取选定的文本?

php - WooCommerce - 添加到购物车没有变体 ID

php - Codeigniter中通过ajax将数据传递给 Controller

c# - 如何在 MVC 5 中的 Bootstrap 3 导航中将链接左右对齐

html - 如何将渐变叠加添加到在 css 样式属性中设置的图像?

html - 如何以相反的顺序获取 html 表 w.r.t.到 Angular js中的键

html - 如何使标题居中?

javascript - $_POST 在 PHP 中不起作用。也尝试过 $_REQUEST

php - 如何从类别名称中获取类别对象

jquery - img 标签的背景大小封面