用PHP获取链接及图片路径的方法

如题,就是获取一段内容中带超链接的图片,把这个超链接和图片链接都获取到,然后在输出 <a href="超链接"><img src="图片链接" /></a> 这样的形式(注:超链接和图片链接不同,不要获取文字链以及没有超链接的图片)
举个例子: 这是内容$neirong,比如里面有个带链接的图片“<a href=http ://xxx.xxx.xxx//><img src=http ://123.123.123/132.jpg /></a>”从里面获取所有类似这样的超链接和图片路径,然后再输出成这样的形式“<a href="超链接"><img src="图片路径" /></a>”,意思就是内容里的其他文字什么的都不要,只提取这个

<?php

$str = "This is a test.This is a test.This is a <a href=http://link1.com><img src=http://img1.jpg /></a>test.This is a test.This is a test.\n" .
    "This is a test.This is a test.<a href=http://link2.com><img src=http://img2.jpg /></a>This is a test.This is a test.This is a test.\n" .
    "<a href=http://link3.com><img src=http://img3.jpg /></a>";

$regex = '/<a\s+href=(.*)\s*><img\s+src=(.*)\s*\/><\/a>/';
$output = array();

if (preg_match_all($regex, $str, $matches) !== false) {
    if (isset($matches[1]) && isset($matches[2])) {
        $links = $matches[1];
        $imgs = $matches[2];

        foreach ($links as $key => $link) {
            $img = isset($imgs[$key]) ? $imgs[$key] : '';
            $output[] = "<a href=\"{$link}\"><img src=\"{$img}\" /></a>";
        }
    }
}

var_dump($output);

追问

写成函数怎么写,具体怎么调用呢,菜鸟一个,希望可以写的详细些

追答<?php
 
 function cr($str){
     $regex = '/<a\s+href=(.*)\s*><img\s+src=(.*)\s*\/><\/a>/';
    $output = array();
 
    if (preg_match_all($regex, $str, $matches) !== false) {
        if (isset($matches[1]) && isset($matches[2])) {
            $links = $matches[1];
            $imgs = $matches[2];
     
            foreach ($links as $key => $link) {
                $img = isset($imgs[$key]) ? $imgs[$key] : '';
                $output[] = "<a href=\"{$link}\"><img src=\"{$img}\" /></a>";
            }
        }
    }
    
    return $output;
 }

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-10-19
如下面内容,两个问题:
1、用正则取得所有图片地址的php语句怎么写?
2、取出的多个地址如何一条一条地保存到数据库中?

<p><img alt="" width="153" src="/upload/2009-11-15/9_3.jpg" height="60" /><img src="/upload/2009-11-15/58263668.png" alt="" /><img width="153" height="60" alt="" src="/upload/2009-11-15/155439_2.jpg" />1、什么是在线编辑器 2、fckeditor配置 3、fckeditor的应用 4、fckeditor结合数据库应用</p>

回答:

<?php
$str ='<p><img alt="" width="153" src="/upload/2009-11-15/9_3.jpg" height="60" /><img src="/upload/2009-11-15/58263668.png" alt="" /><img width="153" height="60" alt="" src="/upload/2009-11-15/155439_2.jpg" />1、什么是在线编辑器 2、fckeditor配置 3、fckeditor的应用 4、fckeditor结合数据库应用</p>';
preg_match_all("/\<img.*?src\=\"(.*?)\"[^>]*>/i", $str, $match);
print_r($match);追问

要带链接的图片,也就是两个地址都要获取到,一个A链接和一个图片路径链接,然后再输出“”这样的形式,你这个我也会写

第2个回答  2013-10-20
if(preg_match_all('/^<a href*+><img src*+></a>$', $neirong, $iwant)){
print_r($iwant);
}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网