用正則表達式匹配文章中的圖片鏈接並替換成指定圖片鏈接的 PHP 函數:
function replaceImageLinks($content, $newImageLink) {
// 匹配 img 標籤中的 src 屬性
$pattern = '/<img.*?src="(.*?)".*?>/i';
// 用指定鏈接替換匹配到的圖片鏈接
$replacement = '<img src="' . $newImageLink . '">';
// 替換
$newContent = preg_replace($pattern, $replacement, $content);
return $newContent;
}該函數接受兩個參數,分別是原始文章內容和要替換成的新圖片鏈接。
函數使用正則表達式來匹配文章中的圖片鏈接,並使用 preg_replace() 函數將匹配到的圖片鏈接替換成指定的新圖片鏈接。最後,函數返回替換後的新內容。
你可以通過以下方式調用該函數:
$content = '這是一篇文章,其中包含圖片:<img src="https://example.com/image.jpg">。';
$newImageLink = 'https://example.com/new-image.jpg';
$newContent = replaceImageLinks($content, $newImageLink);
echo $newContent;其中,$content 是原始的文章內容,$newImageLink 是要替換成的新圖片鏈接。調用函數後,函數會將文章中所有的圖片鏈接替換成指定的新圖片鏈接,並返回替換後的新內容。
二次需求
我一篇文章裏面有很多圖片,我想要每個圖片鏈接都給替換掉,但是替換的新鏈接我不想都一樣!
所以第二個參數就改爲數組,傳入幾十個隨機圖片的鏈接,在隨機替換!
同時,有些網站的img可能會有style等等各式各樣的標註,有些時候我想只替換對應圖片鏈接,有些時候我想全部將img標籤都替換成純淨版的(例如 <img src="/1.jpg" />)
因此函數就修改咯!
該函數接受兩個參數,分別是原始文章內容和一個包含多個圖片鏈接的數組 $imageLinks。
函數使用正則表達式來匹配文章中的圖片鏈接,然後從 $imageLinks 數組中隨機選擇一個圖片鏈接,用該鏈接替換所有匹配到的圖片鏈接。最後,函數返回替換後的新內容。
你可以通過以下方式調用該函數:
$content = '這是一篇文章,其中包含多張圖片:<img src="https://example.com/image1.jpg">,<img src="https://example.com/image2.jpg">,<img src="https://example.com/image3.jpg">。';
$imageLinks = ['https://example.com/new-image1.jpg', 'https://example.com/new-image2.jpg', 'https://example.com/new-image3.jpg'];
$newContent = randomReplaceImageLinks($content, $imageLinks,0);
echo $newContent;其中,$content 是原始的文章內容,$imageLinks 是一個包含多個圖片鏈接的數組。調用函數後,函數會隨機選擇 $imageLinks 數組中的一個圖片鏈接,將文章中所有的圖片鏈接替換成該鏈接,並返回替換後的新內容。