在處理長字串顯示時,常需依據版面寬度自動換行。本文提供一個實用的 text_wrap() 函數,可依指定字元寬度智慧斷行,支援 HTML 標籤輸出,適用於區塊引用、預格式化文字等多種呈現需求。
function text_wrap($text, $max_width, $html_type)
<?php
function text_wrap($text, $max_width, $html_type) {
$cnt = 0; // 追蹤上次斷行位置
// 根據 HTML 類型決定換行符號
if (!strcmp("PRE", $html_type)) {
$line_break = "\n";
} else {
$line_break = "<br>\n";
}
echo "<$html_type>\n";
// 主迴圈:每 $max_width 字元處理一次
for ($i = $max_width; $i < strlen($text); $i += $max_width) {
$width = $max_width;
// 向前尋找合適斷點(空白、換行、定位符)
while ($text[$i] != " " && $text[$i] != "\n" && $text[$i] != "\t") {
$i--;
$width--;
}
// 輸出當前段落
echo substr($text, $cnt, $width) . $line_break;
$cnt = $i + 1; // 更新下次起始位置
}
// 處理最後一行
$last_line = substr($text, $cnt);
if ($last_line[0] != " ") {
echo substr($text, $cnt);
} else {
echo substr($text, $cnt + 1);
}
echo "</$html_type>\n";
}
// 測試範例
$line = "When considering the use of a server side";
$line .= " language, such as php3, you have to weigh";
$line .= " the load on your server against the benefits";
$line .= " of the language. For many, especially with";
$line .= " regards to php3, the benefits are worth the";
$line .= " sacrifice. For some tasks it is unimaginable";
$line .= " how difficult they would be without server side";
$line .= " scripting. There is certainly something to be";
$line .= " said for web content that is dynamic -- it";
$line .= " keeps people coming back. -- The Webmaster";
text_wrap($line, 60, "BLOCKQUOTE"); // 呼叫函數,每行 60 字元,用 BLOCKQUOTE 包裹
?>
此函數雖屬基礎工具,但在缺乏 CSS 控制的早期 PHP 專案,或需產生純文字報表、Email 內容時,仍具實用價值。現代專案建議優先使用 CSS word-wrap、overflow-wrap 或 text-overflow 處理前端換行。