Hongmu Notes
Home Language Notes PHP function to replace image links in an article with randomly selected links
Language Notes PHP

PHP function to replace image links in an article with randomly selected links

PHP function to replace image links in an article with randomly selected links

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!

 隐藏内容:登录后可查看
//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;
}

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.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

(Adaptive mobile version) Responsive Power Tool Holder – PBootCMS Website Template; Download source code for hardware and machinery equipment websites – 0264

(Adaptive mobile version) Responsive Power Tool Holder – PBootCMS Website Template; Download source code for hardware and machinery equipment websites – 0264 Practical Collection pbootcms Template

An adaptive, responsive mobile-powered tool holder design paired with a PbootCMS website template for hardware and machinery applications. This professional, precision-oriented design is ideal for showcasing industrial products such as powered tool holders and machine tool accessories. It enables machinery component manufacturers to showcase their products online and attract manufacturing industry clients. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn – Related...
👁 55
Marketing environmentally friendly shell powder ecological paint website template 0134

Marketing environmentally friendly shell powder ecological paint website template 0134 Practical Collection Yiyou template

An eyoucms website template for marketing-oriented environmentally friendly shell powder ecological paint companies. The design style is green and environmentally friendly, and can display shell powder coating products, coating effects and engineering cases. It helps coating companies promote green building materials online and attract home decoration and engineering customers. Template display Installation instructions Website backend: /login.php Account: admin Password: admin Related articles Summary of common problems in Yiyou CMS installation...
👁 52
Dessert and Cake Food Website Template – 1200

Dessert and Cake Food Website Template – 1200 Practical Collection Yiyou template

This EyouCMS template is ideal for the dessert, cake, and gourmet food industries. Its cozy and appealing design makes it perfect for showcasing dessert and cake products, gourmet food brands, store imagery, and franchise information. It helps baking and dessert brands attract both online consumers and franchisees. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (...
👁 32
(Adaptive mobile version) Responsive Survey and Design Institute Blue Website – PBootCMS Template; Government Agency/Chamber of Commerce/Association Website Source Code Download – 0265

(Adaptive mobile version) Responsive Survey and Design Institute Blue Website – PBootCMS Template; Government Agency/Chamber of Commerce/Association Website Source Code Download – 0265 Practical Collection pbootcms Template

This is an adaptive, responsive PbootCMS website template designed for survey and design institutes, as well as government agencies and industry chambers of commerce and associations for mobile devices. The design features a sophisticated blue color scheme, making it ideal for survey and design institutes, industry associations, and other organizations to showcase their functions and achievements. It helps public institutions establish authoritative online information dissemination platforms. Template Demo | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.c...
👁 52
Financial Registration Company Business Service Website Template 0135

Financial Registration Company Business Service Website Template 0135 Practical Collection Yiyou template

This EyouCMS template is ideal for the financial registration and corporate business registration services industry. Its professional and sophisticated design effectively showcases business registration, financial agency services, qualification application services, and success stories, helping business service providers attract startup clients online. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 27
Responsive eco-friendly tea set website template 1202

Responsive eco-friendly tea set website template 1202 Practical Collection Yiyou template

An eYouCMS responsive website template designed for the green tea and tea ware industry. Its classical and elegant design is ideal for showcasing tea products, tea ceremony culture, brand stories, and sales information. This template helps tea brands effectively present their products online and attract tea enthusiasts. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS | eYouCMS...
👁 62