美文网首页
从文字与图片混合的内容中提取图片,提取文字

从文字与图片混合的内容中提取图片,提取文字

作者: 苏大发 | 来源:发表于2018-05-29 17:38 被阅读0次
    <?php
    
    $str = "你发的撒卡内伤到你asdfdsf<img src='asd/sdf/a.jpg' alt='' />阿道夫s<img src='hws/5634/ab.jpg' alt='' />";
    
    //1.
    $a = html2imgs($str);
    var_dump($a);
    
    //2.
    $b = getImgs($str);
    var_dump($b);
    
    //获取文字
    $s = strip_tags($str);
    echo $s;
    
    
    //获取指定数量文字
    $string = mb_substr(strip_tags($str), 0, 3, 'utf-8');
    echo $string;
    
    
    function html2imgs ($html) {
        $imgs = array();
        if (empty($html)) return $imgs;
     
        preg_match_all("/<img[^>]+>/i",$html,$img);
    
        if (empty($img)) return $imgs;
        $img = $img[0];
    
        foreach ($img as $g) {
            $g = preg_replace("/^<img|>$/i", '',$g);//移除二头字符
            preg_match("/\ssrc\s*\=\s*\"([^\"]+)|\ssrc\s*\=\s*'([^']+)|\ssrc\s*\=\s*([^\"'\s]+)/i", $g, $src);//空格 src 可能空格 = 可能空格 "非"" 或 '非'' 或 非空白 这几种可能,下同 
            $src= empty($src) ? '': $src[count($src) - 1];//匹配到,总会放在最后
    
            if (empty($src) ) {//空的src? 没用,跳过
                continue ;
            }
    
            preg_match("/\salt\s*\=\s*\"([^\"]+)|\salt\s*\=\s*'([^']+)|\salt\s*\=\s*(\S+)/i", $g, $alt);
            $alt = empty($alt) ? $src : $alt[count($alt) - 1];//alt没值?用src
            preg_match("/\stitle\s*\=\s*\"([^\"]+)|\stitle\s*\=\s*'([^']+)|\stitle\s*\=\s*(\S+)/i", $g, $title);
            $title= empty($title) ? $src : $title[count($title) - 1];//title没值?用src
            $imgs[] = array('title' => $title, 'alt' => $alt, 'src' => $src);
        }
    
        return $imgs;
    }
    
    function getImgs($content,$order='ALL'){  
            $pattern="/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";  
            preg_match_all($pattern,$content,$match);  
            if(isset($match[1])&&!empty($match[1])){  
                if($order==='ALL'){  
                    return $match[1];  
                }  
                if(is_numeric($order)&&isset($match[1][$order])){  
                    return $match[1][$order];  
                }  
            }  
            return '';  
        }
    

    相关文章

      网友评论

          本文标题:从文字与图片混合的内容中提取图片,提取文字

          本文链接:https://www.haomeiwen.com/subject/ojmajftx.html