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

时间:2018-01-29 08:43:20

标签: php html

我想分别用src属性替换字符串中的图像标记....

我有这段代码

$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;
?>

我想得到这样的输出:

  

-1f602.png检查的1f601.png-现在-1f62c.png-1f600.png -

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

(ele1,sub1)> asdfadf
(ele1,sub2)> no matters
(ele2,sub3)> blabla
(ele3,sub1)> opps

输出:

$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 ;