從富文本內容中提取所有 <img src="..."> 的網址。
<?php
$html = '...內容包含
...';
$pattern = '/
]+src=["\']([^"\']+)["\'][^>]*>/i';
preg_match_all($pattern, $html, $matches);
$urls = $matches[1]; // 第 1 捕獲群組即為網址
print_r($urls);
$pattern = '/<(?:img|input)[^>]+(?:src|data-src)=["\']([^"\']+)["\'][^>]*>/i';
<?php
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('' . $html);
libxml_clear_errors();
$urls = [];
foreach ($dom->getElementsByTagName('img') as $img) {
$src = $img->getAttribute('src') ?: $img->getAttribute('data-src');
if ($src) $urls[] = $src;
}
// 同時處理 input type=image
foreach ($dom->getElementsByTagName('input') as $input) {
if ($input->getAttribute('type') === 'image') {
$src = $input->getAttribute('src');
if ($src) $urls[] = $src;
}
}
$urls = array_unique($urls);
$base = 'https://example.com/article/123';
$absolute = array_map(fn($u) => (parse_url($u, PHP_URL_SCHEME) ? $u : rtrim($base, '/') . '/' . ltrim($u, '/')), $urls);
簡單場景用正則 preg_match_all 快速提取;複雜、巢狀、編碼不一致的 HTML 請改用 DOMDocument,正確率與維護性遠勝正則。