duanfu1942 2018-01-29 08:43 采纳率: 100%
浏览 88
已采纳

用php中的src属性替换字符串中的图像标签

I want to replace the image tags in the string with their src attributes respectively....

I have this code

$url='<img class="emojioneemoji" src="http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/1f602.png">checking<img class="emojioneemoji" src="http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/1f601.png">now<img class="emojioneemoji" src="http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/1f62c.png"><img class="emojioneemoji" src="http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/1f600.png">';
$doc = new DOMDocument();
@$doc->loadHTML($url);

$tags = $doc->getElementsByTagName('img');

foreach ($tags as $tag) {
 $img_path =  $tag->getAttribute('src');
 $directory = $img_path;
 $ee = pathinfo($directory);
 $pic_name=  $ee['basename'];
 preg_replace("/<img[^>]+\>/i", " ", $pic_name);
}
echo $url;
?>

I want to get output like this:

-1f602.png-checking-1f601.png-now-1f62c.png-1f600.png-

  • 写回答

1条回答 默认 最新

  • duanshang3230 2018-01-29 08:49
    关注

    You could try something like this :

    $str = "-" ;
    foreach ($tags as $tag) {
        $img_path =  $tag->getAttribute('src');
        $directory = $img_path;
        $ee = pathinfo($directory);
        $pic_name=  $ee['basename'];
    
        // Get the next element if exists and is a DOMText :
        $next = "" ;
        if ($tag->nextSibling && get_class($tag->nextSibling) == "DOMText") {
            $next = $tag->nextSibling->wholeText . "-" ;
        }
    
        $str .= $pic_name . "-" . $next ;
    }
    
    echo $str ;
    

    Will outputs :

    -1f602.png-checking-1f601.png-now-1f62c.png-1f600.png-
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?