需求:快速檢測遠程或本地 HTML 內容中是否存在 <img> 標籤。核心思路:使用 preg_match() 匹配 <img 模式,簡單高效,同樣邏輯可擴展至郵箱、手機號等特徵檢測。
<?php
$url = "https://example.com/article/012.html";
$content = file_get_contents($url); // 獲取頁面源碼
if (preg_match("/<img.*>/", $content)) {
echo "檢測到圖片";
} else {
echo "未發現圖片";
}
?>
<?php
function hasImage($html) {
// 更精確:匹配 ![]()
file_get_contents() 需開啟 allow_url_fopen,否則改用 cURL。i 修飾符),兼容 <IMG>、<Img> 等寫法。preg_match 比 preg_match_all 更快(匹配即停止)。