大量純文字稿(新聞稿、部落格備稿、郵件內容)需快速發布為網頁,手工加標籤太慢。PHP 可自動:
<h1>)<p class="byline">)<p> 包裹,保留換行<?php
function textToHtml(string $sourcePath, string $outputPath = ''): string
{
$lines = file($sourcePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (!$lines) throw new RuntimeException('檔案為空');
$title = array_shift($lines);
$byline = array_shift($lines) ?? '';
$body = implode("\n", $lines);
// 1. HTML 實體編碼
$body = htmlspecialchars($body, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
// 2. 連續換行 → 段落
$body = preg_replace('/\n{2,}/', "</p>\n<p>", $body);
// 3. 單換行 → <br>
$body = nl2br($body);
// 4. 包裹段落標籤
$body = "<p>$body</p>";
// 5. URL 自動連結 (簡易版)
$body = preg_replace(
'#\b(https?://\S+)#i',
'<a href="$1" target="_blank" rel="noopener">$1</a>',
$body
);
// 6. Email 自動連結
$body = preg_replace(
'#\b([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,})\b#',
'<a href="mailto:$1">$1</a>',
$body
);
// 7. 組裝完整頁面
$html = <<
進階:Markdown 替代方案
若來源可控,建議直接寫 **Markdown**,用 erusev/parsedown 或 league/commonmark 轉 HTML,語意更豐富(標題層級、清單、程式碼區塊、表格)。
composer require league/commonmark
$html = (new League\CommonMark\Environment\Environment())
->addExtension(new League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension())
->createConverter()
->convertToHtml($markdownText);
批次處理腳本
foreach (glob('articles/*.txt') as $txt) {
$htmlFile = basename($txt, '.txt') . '.html';
textToHtml($txt, "public/$htmlFile");
echo "Generated: $htmlFile\n";
}