PHP regular implementation of image replacement

藏色散人
Release: 2023-03-07 22:00:02
Original
2686 people have browsed it

How to replace images with regular images in php: first specify the web page and start curl; then execute a curl session; then perform regular matching; finally match all img and implement replacement.

PHP regular implementation of image replacement

Recommended: "PHP Video Tutorial"

The operating environment of this tutorial: Windows 7 system, PHP version 5.6, This method works for all brands of computers.

php regex extracts images and replaces

<?php
//  指定网页
$url = "http://aihuinong.com/goods/";
//  启动curl
$ch = curl_init();
//  CURLOPT_URL: 这是你想用PHP取回的URL地址。你也可以在用curl_init()函数初始化时设置这个选项。
curl_setopt ($ch, CURLOPT_URL, $url);
//(后面参数为1时) 如果成功只将结果返回,不自动输出任何内容。如果失败返回FALSE
//(后面参数为0时) 如果成功只返回TRUE,自动输出返回的内容。如果失败返回FALSE
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
//  CURLOPT_CONNECTTIMEOUT 在发起连接前等待的时间,如果设置为0,则不等待。
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
//  curl_exec — 执行一个curl会话
$dxycontent = curl_exec($ch);
//  匹配class="yt-goods-nav" - class="pagination"之间的内容
$pattern = &#39;/<div class="yt-goods-nav">(.+?)<div class="pagination" style="float: right">/is&#39;;
//  执行正则匹配
preg_match($pattern, $dxycontent, $match);
//var_dump($match[0]);
//$match[0] 即为<div class="yt-goods-nav">和<div class="pagination">之间的所有源码
//  匹配所有的img
preg_match_all(&#39;/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i&#39;,
$match[0],$matches);//带引号
$new_arr=array_unique($matches[0]);//去除数组中重复的值
//
foreach($new_arr as $key) {
//strip_tags($key);
//由于这个网站的路径的域名被隐藏 所以直接替换/为域名/
echo preg_replace(&#39;#src="/#is&#39;, &#39;src="http://aihuinong.com/&#39;, $key);
echo "</br>";
}
Copy after login

I have nothing to do today, so I played with regex. Take a look at the pictures on your company website.

The comments in the code are clearly written.

The above is the detailed content of PHP regular implementation of image replacement. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template