Hongmu Notes
Home page › Language Notes › PHP replaces image links in articles and randomly replaces links (function)
Language Notes PHP

PHP replaces image links in articles and randomly replaces links (function)

PHP replaces image links in articles and randomly replaces links (function)

A PHP function that uses regular expressions to match image links in an article and replace 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 be used as a replacement.

The function uses regular expressions to match image links in the article and uses preg_replace() The function replaces the matched image link with the specified new image link. Finally, the function returns the newly replaced content.

You can call this function in the following ways:

$content = '这是一篇文章,其中包含图片:<img src="https://example.com/image.jpg">。';
$newImageLink = 'https://example.com/new-image.jpg';
$newContent = replaceImageLinks($content, $newImageLink);
echo $newContent;

among,$content This is the original article content,$newImageLink This is the new image link that will replace the existing ones. After calling the function, the function replaces all image links in the article with the specified new image link and returns the newly replaced content.

Secondary demand

An article of mine contains many images, and I want to replace the link for each image, but I don't want all the new links to be the same!

Therefore, the second parameter should be changed to an array containing links to dozens of randomly selected images, which will then be randomly replaced!

At the same time, the images on some websites may havestyleThere are all kinds of annotations; sometimes I just want to replace the corresponding image links, while at other times I want to replace all img tags with a clean version (for example, <img src="https://www.4s5.cn/1.jpg" />)

So the function has been modified!

 Hidden content: You can view it after logging in
//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 the article, and then from $imageLinks Randomly select one image link from the array, then replace all matching image links with that link. Finally, the function returns the newly replaced content.

You can call this function in the following ways:

$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 This is the original article content,$imageLinks It is an array containing multiple image links. After the function is called, the function will randomly select $imageLinks Given a single image link within an array, replace all image links in the article with that link and return the newly replaced 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

The following three functions can be used: ob_get_contents(); ob_end_clean(); and ob_start(); These functions can be employed to buffer local files and execute local script code. Use ob_start() to store the output code in a buffer, so that it will not be displayed on the page; then use ob_get_contents() to retrieve the data from the buffer. o...
👁 430
PHP preg

PHP preg Language Notes PHP

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

Detailed explanation of PHP ternary operator and if Language Notes PHP

Conditions for the ternary operator:? Result 1: Result 2. Explanation: The position preceding the question mark represents the condition for evaluation; if the condition is met, the result is Result 1; if it is not met, the result is Result 2. This article provides a detailed comparison between the ternary operator and if...else..., and we hope it will be helpful to everyone. While working on an online thesis revision today, I encountered a statement that I could not understand: $if_summary = $row[&#039;IF_SUMMARY&#039;]=...
👁 512
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Obtaining data types\n1. To view the value and type of a particular expression, use var_dump().\n2. If you simply need a human-readable representation of a type for debugging, use gettype().\n3. To inspect a particular type, do not use gettype(); instead, use the is_type() function.\nConverting strings to numeric values\nWhen a string is evaluated as a number, the result is determined according to the following rules...
👁 579

Recommended reading

js jump to the specified page after 5 seconds

js jump to the specified page after 5 seconds Language Notes JavaScript

Analysis: 1. If you need to perform a redirect, use the href attribute of the location object. 2. To implement a 5-second countdown, use the setInterval timer. HTML: &amp;lt;div id=&amp;quot;msg&amp;quot;&amp;gt;&amp;lt;/div&amp;gt; JavaScript: window.onload=function(){...
👁 414
What does cdn return traffic mean?

What does cdn return traffic mean? Summary of pitfalls

CDN back-end traffic refers to the amount of data transmitted when a user requests content hosted on a CDN (Content Delivery Network) node; if that node does not have the content cached or if the cached content has expired, the CDN sends a request to the origin server to retrieve the original content, transmits it back to the CDN node via the network, and finally delivers it to the user. The volume of data transmitted during this process constitutes the back-end traffic. The primary function of a CDN is to cache content on nodes located closer to users...
👁 686
Which one is better, back-to-origin authentication function or timestamp anti-leeching?

Which one is better, back-to-origin authentication function or timestamp anti-leeching? Summary of pitfalls

Source authentication and timestamp-based anti-botting are common technical measures used to prevent unauthorized access to resources. Each has its own advantages and disadvantages, and the appropriate solution can be selected based on actual requirements. Source authentication: Advantages: Source authentication determines whether access to the original content on the source server is permitted by verifying the authentication information included in the request. This approach is relatively flexible; different authentication rules can be configured according to specific requirements, providing finer-grained access control. Disadvantages: Source...
👁 502
(PC+WAP) Green environmental protection equipment pbootcms corporate website template Environmental protection corporate website source code download 0088

(PC+WAP) Green environmental protection equipment pbootcms corporate website template Environmental protection corporate website source code download 0088 Practical Collection pbootcmstemplate

This PbootCMS template is a green-themed corporate website specifically designed for environmental protection equipment companies, supporting both PC and mobile devices. Its fresh and natural design effectively showcases environmental equipment products such as wastewater treatment and air purification systems. It helps environmental protection companies establish a professional online image and expand their channels for business partnerships. Template Preview | Installation Instructions | Website Backend: /admin.php | Account: admin | Password: admin | Unzip password:...
👁 375
(Adaptive mobile phone) Electronic eye electronic monitoring equipment pbootcms website template Monitoring and security electronic probe website source code download 0368

(Adaptive mobile phone) Electronic eye electronic monitoring equipment pbootcms website template Monitoring and security electronic probe website source code download 0368 Practical Collection pbootcmstemplate

A PbootCMS website template for an adaptive mobile-based electronic eye surveillance and security device. The design features a tech-forward and secure aesthetic, making it ideal for showcasing surveillance cameras, security systems, and smart hardware. It helps security technology companies showcase their products online and attract residential and commercial clients. Template showcase; installation instructions; website backend: /admin.php; account: admin; password: admin; extraction password: www.4s5.cn; related...
👁 333