A PHP function that uses regular expressions to match image links within an article and replaces them with specified image links:
function replaceImageLinks($content, $newImageLink) {
// 匹配 img 标签中的 src 属性
$pattern = '/<img.*?src="(.*?)".*?>/i';
// 用指定链接替换匹配到的图片链接
$replacement = '<img src="' . $newImageLink . '">';
// 替换
$newContent = preg_replace($pattern, $replacement, $content);
return $newContent;
}This function accepts two parameters: the original article content and the new image link to replace it with.
The function uses regular expressions to match image links within an article and then utilizes them. preg_replace() The function replaces the matched image links with specified new image links. Finally, the function returns the newly updated content.
You can call this function using the following methods:
$content = '这是一篇文章,其中包含图片:<img src="https://example.com/image.jpg">。';
$newImageLink = 'https://example.com/new-image.jpg';
$newContent = replaceImageLinks($content, $newImageLink);
echo $newContent;among,$content The original article content.$newImageLink This is the new image link to be used for replacement. When the function is called, it will replace all image links within the article with the specified new image link and return the updated content.
Secondary demand
My article contains many images; I would like to replace the link for each image, but I don't want all the new links to be identical!
Therefore, the second parameter is now set to an array, which contains links to dozens of random images – these images will be randomly replaced!
Additionally, some websites may contain <img> tags.styleVarious types of annotations – sometimes I just want to replace the corresponding image links, while other times I want to replace all <img> tags with their clean versions (e.g. <img src="/1.jpg" />)
So, let's modify the function!
This function accepts two parameters: the original article content and an array containing multiple image links. $imageLinks。
The function uses regular expressions to match image links within an article, and then extracts them. $imageLinks Randomly select an image link from the array and replace all matched image links with this link. Finally, the function returns the updated content.
You can call this function using the following methods:
$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;among,$content The original article content.$imageLinks It is an array containing multiple image links. When the function is called, it will randomly select one of them. $imageLinks A single image URL in an array; replaces all image URLs within the article with this single URL and returns the updated content.