從含 HTML 標記的字串中提取純文字內容,常用於資料清洗、搜尋摘要、RSS 處理等場合。
<?php
$htm = "<a href='https://www.php100.net'>test1</a><br />"
. "<a href='https://www.php100.net'>test2</a><br />"
. "<a href='https://www.php100.net'>test3</a><br />"
. "<a href='https://www.php100.net'>test4</a><br />"
. "<a href='https://www.php100.net'>test5</a><br />";
echo $htm . "<br />";
echo stripthetag($htm);
/** 移除所有 HTML 標籤 */
function stripthetag($link) {
return preg_replace('@<[/!]*?[^<>]*?>@si', ' ', $link);
}
?>
@<[/!]*?[^<>]*?>@si
@ ... @:定界符<:匹配標籤起始[/!]*?:可選的 /(結束標籤)或 !(註解/Doctype),非貪婪[^<>]*?:非標籤字元,非貪婪>:匹配標籤結束s:單行模式(. 匹配換行)i:不區分大小寫替換為單一空格,避免標籤移除後單詞黏連。
輸出前: <a href='https://www.php100.net'>test1</a><br /> ... 輸出後: test1 test2 test3 test4 test5
<br> 換行),可改用 strip_tags($str, '<br><p>') 內建函數。htmlspecialchars() 防 XSS。preg_replace 效能優於多次 str_replace。此函數簡潔高效,適合快速剝離 HTML 標記取得純文字內容。