preg_replace突然感觉好强大啊
阅读原文时间:2023年07月10日阅读:1


需要把上面这段html中的图片网址,上传到自己的服务器,并做好映射。

提取url:

preg_match_all('/]*src\s?=\s?[\'|"](?!http:\/\/img.jinyuanbao|http:\/\/img.jybtest)([^\'|"]*)[\'|"]/is', $content, $picarr);

这段代码的意思是提取非img.jinyuanbao和img.jybtest开头的网址。提取完毕,等到数组$picarr;

Array
(
[0] => Array
(
[0] => <img align="absmiddle" src="https://img.alicdn.com/imgextra/i1/1696415374/TB2BDgldpXXXXXSXXXXXXXXXXXX_!!1696415374.jpg"
)

 \[1\] => Array  
     (  
         \[0\] => https://img.alicdn.com/imgextra/i1/1696415374/TB28Af4dpXXXXbkXpXXXXXXXXXX\_!!1696415374.jpg  
         \[1\] => https://img.alicdn.com/imgextra/i2/1696415374/TB2LC29dpXXXXXJXpXXXXXXXXXX\_!!1696415374.jpg  
         \[2\] => https://img.alicdn.com/imgextra/i4/1696415374/TB25N.pdpXXXXXfXXXXXXXXXXXX\_!!1696415374.jpg  
         \[3\] => https://img.alicdn.com/imgextra/i3/1696415374/TB2axr0dpXXXXcnXpXXXXXXXXXX\_!!1696415374.jpg  
         \[4\] => https://img.alicdn.com/imgextra/i4/1696415374/TB2rv62dpXXXXbJXpXXXXXXXXXX\_!!1696415374.jpg  
         \[5\] => https://img.alicdn.com/imgextra/i3/1696415374/TB2Yg27dpXXXXawXpXXXXXXXXXX\_!!1696415374.jpg  
         \[6\] => https://img.alicdn.com/imgextra/i2/1696415374/TB2SsY\_dpXXXXXTXpXXXXXXXXXX\_!!1696415374.jpg  
         \[7\] => https://img.alicdn.com/imgextra/i2/1696415374/TB2tAD8dpXXXXabXpXXXXXXXXXX\_!!1696415374.jpg  
         \[8\] => https://img.alicdn.com/imgextra/i3/1696415374/TB2ds61dpXXXXb8XpXXXXXXXXXX\_!!1696415374.jpg  
         \[9\] => https://img.alicdn.com/imgextra/i2/1696415374/TB2cyZjdpXXXXaQXXXXXXXXXXXX\_!!1696415374.jpg  
         \[10\] => https://img.alicdn.com/imgextra/i2/1696415374/TB2TUZhdpXXXXXxXXXXXXXXXXXX\_!!1696415374.jpg  
         \[11\] => https://img.alicdn.com/imgextra/i1/1696415374/TB2C07odpXXXXXyXXXXXXXXXXXX\_!!1696415374.jpg  
         \[12\] => https://img.alicdn.com/imgextra/i3/1696415374/TB2egT6dpXXXXa4XpXXXXXXXXXX\_!!1696415374.jpg  
         \[13\] => https://img.alicdn.com/imgextra/i1/1696415374/TB2D3EodpXXXXXyXXXXXXXXXXXX\_!!1696415374.jpg  
         \[14\] => https://img.alicdn.com/imgextra/i1/1696415374/TB2BDgldpXXXXXSXXXXXXXXXXXX\_!!1696415374.jpg  
     )

)

我们把$picar[1]中的图片连接存在oss;

https://img.alicdn.com/imgextra/i1/1696415374/TB2BDgldpXXXXXSXXXXXXXXXXXX_!!1696415374.jpg

存储在OSS上

http://img.jybtest.com/425968826991101.jpg

得到一个映射的数组$pics:

$pics = array(
'https://img.alicdn.com/imgextra/i1/1696415374/TB2BDgldpXXXXXSXXXXXXXXXXXX_!!1696415374.jpg' => 'http://img.jybtest.com/425968826991101.jpg'

_);

foreach ($pics as $k => $v) {_

$content = str_replace($k, $v, $content);
  }

//或者

$k = array_map(function($item) {return '/'.str_replace('/', '\/', $item).'/';}, array_keys($pics));

$v = array_values($pics); $content = preg_replace($k, $v, $content); print_r($content);

preg_replace看出这个很方便地!

http://h5.mainphp.com/ 欢迎光顾

本博客不在更新!!!!