萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

PHP 分頁、防英文單詞截斷、去除 HTML 標籤三合一工具類

早期 PHP 專案常需:長文分頁、保證英文單詞完整、剝離 HTML 標籤輸出純文本。封裝三大工具函數,開箱即用。

1. 去除 HTML 標籤 pregstring()

function pregstring($str) {
    $str = trim($str);
    $search = [
        '/<script\b[^>]*>[\s\S]*?<\/script>/i',
        '/<style\b[^>]*>[\s\S]*?<\/style>/i',
        '/<[!\/]?[^<>]*>/i',          // 所有標籤
        '/&(quot|#34);/i',              // "
        '/&(amp|#38);/i',               // &
        '/\s{2,}/',                      // 多餘空白
        '/\$/','/ /'
    ];
    $replace = ['', '', '', '"', '&', ' ', ' dollar ', ' '];
    return preg_replace($search, $replace, $str);
}

2. 防英文單詞截斷 englishSubstr()

function englishSubstr($str, $start, $length) {
    if ($start != 0 && $str[$start-1] !== ' ') { // 截在單詞中間
        for ($i=1; $i<20; $i++) {
            if ($str[$start+$i] === ' ') { $start += $i; break; }
        }
    }
    $end = $start + $length;
    if ($end < strlen($str) && $str[$end] !== ' ') { // 結尾在單詞中
        for ($i=1; $i<20; $i++) {
            if ($str[$end+$i] === ' ') { $end += $i; break; }
        }
    }
    return substr($str, $start, $end - $start);
}

3. 分頁邏輯整合

$content = pregstring($rawContent);
$contentSize = strlen($content);
$pageSize = 500; // 每頁字符數
$pageCount = ceil($contentSize / $pageSize);
$page = max(1, min((int)($_GET['page'] ?? 1), $pageCount));

$center = englishSubstr($content, ($page-1)*$pageSize, $pageSize);

// 分頁導航輸出
$nav = '';
if ($page > 1) $nav .= '<a href="?page='.($page-1).'">上一頁</a> ';
if ($page < $pageCount) $nav .= '<a href="?page='.($page+1).'">下一頁</a>';

// 模板賦值 (Smarty 風格)
$tpl->assign('CONTENT', $center);
$tpl->assign('PAGER', $nav);
$tpl->display('article.tpl');

現代化建議

  • 分頁改用資料庫 LIMIT/OFFSET 或游標分頁,避免全文載入記憶體。
  • 去 HTML 用 strip_tags() + html_entity_decode() 或 HtmlPurifier。
  • 單詞斷行用 CSS word-break: break-word; overflow-wrap: anywhere; 前端解決,後端只管語義分段。
copyright © 萬盛學電腦網 all rights reserved