[英]How to insert word-wrap function to auto-break a long word in PHP?
How can I insert word-wrap function so that any word that is too long doesn't cut <div>
border but line-returns itself? 我该如何插入自动换行功能,以便任何太长的单词都不会切掉<div>
边框,而是自动换行?
The following is the variable I want to word-wrap 以下是我想自动换行的变量
$body = nl2br(addslashes($_POST['body']));
try out these links: 试用以下链接:
Smarter word-wrap in PHP for long words? 用PHP换行可以更智能地换长字吗?
http://php.net/manual/en/function.wordwrap.php http://php.net/manual/zh/function.wordwrap.php
http://www.w3schools.com/php/func_string_wordwrap.asp http://www.w3schools.com/php/func_string_wordwrap.asp
And a custom Function: 和一个自定义函数:
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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.