首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 文字自動換行函數:依指定字元寬度智慧斷行

     編輯:PHP 相關知識

實用 PHP 文字換行工具:text_wrap() 函數完整解析

在處理長字串顯示時,常需依據版面寬度自動換行。本文提供一個實用的 text_wrap() 函數,可依指定字元寬度智慧斷行,支援 HTML 標籤輸出,適用於區塊引用、預格式化文字等多種呈現需求。

函數簽名與參數說明

function text_wrap($text, $max_width, $html_type)
  • $text:待格式化的文字內容
  • $max_width:每行最大字元寬度
  • $html_type:輸出 HTML 標籤類型(如 "BLOCKQUOTE"、"PRE"、"DIV" 等)

核心邏輯與特色

  • 智慧斷行:避免在單字中間斷行,會向前尋找空白、換行或定位字元作為斷點
  • HTML 標籤包裹:自動以指定標籤包裹輸出內容
  • 換行符號自適應:PRE 標籤使用 "\n",其他標籤使用 "<br>\n"
  • 處理尾行邏輯:正確處理最後一行顯示,避免重複或遺漏

完整程式碼實作

<?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 包裹
?>

使用情境與擴充建議

  • 文章內容預覽截斷顯示
  • 留言板、論壇長文自動排版
  • 報表輸出固定寬度欄位
  • 可擴充支援中文雙位元字元寬度計算
  • 可加入單字不斷行保護(如 URL、長英文單字)

此函數雖屬基礎工具,但在缺乏 CSS 控制的早期 PHP 專案,或需產生純文字報表、Email 內容時,仍具實用價值。現代專案建議優先使用 CSS word-wrap、overflow-wrap 或 text-overflow 處理前端換行。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved