如何插入自动换行功能来​​自动中断PHP中的长字?

时间:2015-12-04 03:49:21

标签: php html html5

如何插入自动换行功能,以便任何太长的单词都不会切割<div>边框但会自行返回?

以下是我想要自动换行的变量

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

1 个答案:

答案 0 :(得分:-3)

试试这些链接:

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";