早期 PHP 專案常需:長文分頁、保證英文單詞完整、剝離 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);
}
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);
}
$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 或游標分頁,避免全文載入記憶體。strip_tags() + html_entity_decode() 或 HtmlPurifier。word-break: break-word; overflow-wrap: anywhere; 前端解決,後端只管語義分段。