萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP UBB 代碼轉 HTML 解析器:標籤替換、引用區塊、程式碼區塊、圖片/連結/郵件自動識別

UBB (Ultimate Bulletin Board) 代碼是論壇常用的輕量標記語言。本文提供 PHP 正則替換實作,支援基本排版、引用、程式碼、圖片、超連結、郵件標籤轉換。

核心轉換函數

function ubb2html($content) {
    global $article; // 假設 $article['isparseurl'] 控制自動識別 URL
    
    // 自動識別 URL(可選)
    if ($article['isparseurl'] == "1") {
        $content = parseurl($content); // 需自行實作或使用現成庫
    }
    
    // 基本排版標籤
    $content = preg_replace('/\[b\]/i', '', $content);
    $content = preg_replace('/\[\/b\]/i', '', $content);
    $content = preg_replace('/\[i\]/i', '', $content);
    $content = preg_replace('/\[\/i\]/i', '', $content);
    $content = preg_replace('/\[u\]/i', '', $content);
    $content = preg_replace('/\[\/u\]/i', '', $content);
    $content = preg_replace('/\[center\]/i', '
', $content); $content = preg_replace('/\[\/center\]/i', '
', $content); // 引用區塊 $content = preg_replace( '/\[quote\]/i', '
引用:

', $content ); $content = preg_replace( '/\[\/quote\]/i', '

', $content ); // 程式碼區塊 $content = preg_replace( '/\[code\]/i', '
代碼:

', $content ); $content = preg_replace( '/\[\/code\]/i', '

', $content ); // 圖片 $content = preg_replace( '/\[img\]([^\[]*)\[\/img\]/i', '', $content ); // 超連結 $content = preg_replace('/\[url\]www\.([^\[]*)\[\/url\]/i', 'www.\1', $content); $content = preg_replace('/\[url\]([^\[]*)\[\/url\]/i', '\1', $content); $content = preg_replace('/\[url=([^\[]*)\]([^\[]*)\[\/url\]/i', '\2', $content); // 郵件 $content = preg_replace('/\[email\]([^\[]*)\[\/email\]/i', '\1', $content); return $content; }

改進建議:使用 preg_replace_callback 統一處理

function ubb2html($content) {
    $patterns = [
        '/\[b\](.*?)\[\/b\]/is' => '$1',
        '/\[i\](.*?)\[\/i\]/is' => '$1',
        '/\[u\](.*?)\[\/u\]/is' => '$1',
        '/\[quote\](.*?)\[\/quote\]/is' => '
$1
', '/\[code\](.*?)\[\/code\]/is' => '
$1
', '/\[img\](https?:\/\/[^\s\]]+)\[\/img\]/i' => '', '/\[url=(https?:\/\/[^\]]+)\](.*?)\[\/url\]/is' => '$2', '/\[url\](https?:\/\/[^\]]+)\[\/url\]/i' => '$1', '/\[email\]([^\]]+)\[\/email\]/i' => '$1', ]; foreach ($patterns as $pattern => $replacement) { $content = preg_replace($pattern, $replacement, $content); } return $content; }

安全性強化(必要)

  • XSS 防護:轉換前先 htmlspecialchars(),再還原允許的標籤,或使用 HTMLPurifier
  • 嚴格正則:避免貪婪匹配導致跨標籤吞噬,使用 .*? 非貪婪模式
  • 屬性過濾:僅允許 href/src/alt/title,移除 onclick、style 等危險屬性
  • rel="noopener":外部連結防止 window.opener 鏈接攻擊

現代替代方案

  • Markdown + Parsedown/League CommonMark:語法更優雅、標準化、生態豐富
  • BBCode 库:jbbcode (Java)、bbcode (PHP) 等成熟解析器
  • 編輯器整合:CKEditor、TinyMCE、Editor.js 輸出乾淨 HTML,避免自訂標記

UBB 解析器適合舊系統遷移或特定社群慣例;新專案建議直接採用 Markdown 或富文本編輯器。

copyright © 萬盛學電腦網 all rights reserved