php字符串超长自动换行
1. 英文字符串超长换行使用系统方法wordwrap
2. 中文字符串超长换行自行定义方法mb_wordwrap
/**
* Notes:对传入的中文字符串处理,如果字符串超过限定的长度,则自动进行换行
* docs:
*/
function mb_wordwrap($str, $width = 8, $break = "\r\n"){
// Return short or empty strings untouched
if (empty($str) || mb_strlen($str, 'UTF-8') <= $width) {
return $str;
}
$br_width = mb_strlen($break, 'UTF-8');
$str_width = mb_strlen($str, 'UTF-8');
$return = '';
$last_space = false;
for ($i = 0, $count = 0; $i < $str_width; $i++, $count++) {
// If we're at a break
if (mb_substr($str, $i, $br_width, 'UTF-8') == $break) {
$count = 0;
$return .= mb_substr($str, $i, $br_width, 'UTF-8');
$i += $br_width - 1;
continue;
}
// Keep a track of the most recent possible break point
if (mb_substr($str, $i, 1, 'UTF-8') == " ") {
$last_space = $i;
}
// It's time to wrap
if ($count > $width) {
// There are no spaces to break on! Going to truncate :(
if (!$last_space) {
$return .= $break;
$count = 0;
} else {
// Work out how far back the last space was
$drop = $i - $last_space;
// Cutting zero chars results in an empty string, so don't do that
if ($drop > 0) {
$return = mb_substr($return, 0, -$drop);
}
// Add a break
$return .= $break;
// Update pointers
$i = $last_space + ($br_width - 1);
$last_space = false;
$count = 0;
}
}
// Add character from the input string to the output
$return .= mb_substr($str, $i, 1, 'UTF-8');
}
return $return;
}
本文作者:vlson
本文链接:https://www.cnblogs.com/wxdblog/p/17588097.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步