可以使用 PHP 的正則表達式函數 preg_match_all() 來匹配文章中的所有圖片鏈接,正則表達式可以根據圖片鏈接的格式進行匹配。
以下是一個例子:
function getImagesFromContent($content) {
$pattern = '/<img.*?src=[\'"](.*?)[\'"].*?>/i';
preg_match_all($pattern, $content, $matches);
return $matches[1];
}這個函數接收一個字符串參數 $content,表示文章內容。它會使用正則表達式 /<img.*?src=[\'"](.*?)[\'"].*?>/i 匹配文章中的所有圖片鏈接。其中,.*? 表示匹配任意字符(包括空白字符)零次或多次,使用 ? 表示非貪婪模式(儘可能少匹配字符);[\'"] 表示匹配單引號或雙引號;i 表示忽略大小寫。匹配結果會被保存在 $matches 數組中的第二個元素 $matches[1] 中,函數返回這個數組。
使用示例:
$content = '<p><img src="https://example.com/image1.jpg" /></p>
<p><img src="https://example.com/image2.jpg" /></p>
<p><img src="https://example.com/image3.jpg" /></p>';
$images = getImagesFromContent($content);
var_dump($images);輸出結果:
array(3) {
[0]=>
string(24) "https://example.com/image1.jpg"
[1]=>
string(24) "https://example.com/image2.jpg"
[2]=>
string(24) "https://example.com/image3.jpg"
}