Home  >  Article  >  Backend Development  >  PHP regular expression extraction image url program

PHP regular expression extraction image url program

PHP中文网
PHP中文网Original
2017-03-22 15:46:411778browse

先用正则表达式获取IMG标签,然后把每个IMG标签的SRC抽取出来,并且组合成自己的内容,最后进行替换

我想对 html 的图片进行提取.

<img ico src="/noavatar_small.gif" />
<img src="/noavatar_small.gif" />

如上地址. 我想全部提取出来 但是包含'ico' 的地址 忽略. 求正则 , 就是有些图片 提取.有些不提取.

例子: 

<s*imgs+[^>]*?srcs*=s*(&#39;|")(.*?)\1[^>]*?/?s*>

经改进后..

正确解答如下

/<img(?:(?!(ico)).)+/>/

实例

//要替换的内容 
$content = &#39;<img alt="" src="js/fckeditor/UserFiles/image/F201005201210502415831196.jpg" width="600" height="366"><br><br><br><br><img alt="" src="js/fckeditor/UserFiles/image/33_avatar_middle.jpg" width="120" height="120">&#39;;

//提取图片路径的src的正则表达式
preg_match_all("/<img(.*)src="([^"]+)"[^>]+>/isU",$content,$matches);

$img = "";
if(!empty($matches)) {
//注意,上面的正则表达式说明src的值是放在数组的第三个中
$img = $matches[2];
}else {
$img = "";
}
if (!empty($img)) {
$img_url = "http://".$_SERVER[&#39;SERVER_NAME&#39;];

$patterns= array();
$replacements = array();

foreach($img as $imgItem){

$final_imgUrl = $img_url.$imgItem;
$replacements[] = $final_imgUrl;

$img_new = "/".preg_replace("///i","/",$imgItem)."/";
$patterns[] = $img_new;

}

//让数组按照key来排序
ksort($patterns);
ksort($replacements);

//替换内容
$vote_content = preg_replace($patterns, $replacements, $content);

相关文章:

php正则表达式提取html标签的问题

提取html标签的php代码示例

通过php提取HTML标签

Statement:
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