详情页

PHP替换文章中图片链接,并随机替换链接(函数)

时间:2023年10月04日

编辑:佚名

用正则表达式匹配文章中的图片链接并替换成指定图片链接的 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" />)
因此函数就修改咯!
//type 0为替换img全部,1为只替换链接,默认替换链接
function randomReplaceImageLinks($content, $imageLinks, $type = 1) {
  // 匹配 img 标签中的 src 属性
  $pattern = '/<img.*?src="(.*?)".*?>/i';
  // 获取所有匹配到的图片链接
  preg_match_all($pattern, $content, $matches);
  if (empty($matches[$type])) {
    return $content;
  }
  
  // 遍历所有匹配到的图片链接,用随机选择的图片链接替换
  foreach ($matches[$type] as $oldImageLink) {
    // 随机选择一个图片链接
    $randomIndex = array_rand($imageLinks);
    $newImageLink = $imageLinks[$randomIndex];
    $newImageLink = $type==0?'<img src="' . $newImageLink . '">':$newImageLink;
    $content = str_replace($oldImageLink, $newImageLink, $content);
  }
  return $content;
}
该函数接受两个参数,分别是原始文章内容和一个包含多个图片链接的数组 $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 数组中的一个图片链接,将文章中所有的图片链接替换成该链接,并返回替换后的新内容。
相关文章
猜你需要