DOM中最后一个兄弟之后的文本没有显示

时间:2018-01-31 04:11:40

标签: php html dom

我有这个代码用它的源替换[img]标签,但输出后没有显示最后一个图像标签后的文本

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

$tags = $doc->getElementsByTagName('img');
 $str = "" ;
foreach ($tags as $tag) {
 $img_path =  $tag->getAttribute('src');
 $directory = $img_path;
 $ee = pathinfo($directory);
 $pic_name=  $ee['basename'];
 $next = "" ;
 $previous = "";
 //echo $tag->nextSibling->wholeText;
 if ($tag->previousSibling && get_class($tag->previousSibling) == "DOMText") {
    $previous = $tag->previousSibling->wholeText . "-" ;
 }
 elseif($tag->nextSibling && get_class($tag->nextSibling) == "DOMText") {
    $next = $tag->nextSibling->wholeText . "-" ;
 }
 $str .= $previous. $pic_name . "-" . $next ;
}
echo  $str ;

以上输出为
AA-1f62c.png-BB-1f600.png-
我怎样才能获得文字&#39; cc&#39;在最后[img]标签之后。 ?

1 个答案:

答案 0 :(得分:0)

if-else语句中存在逻辑错误。请尝试以下代码:

<?php

$url = 'aa<img class="emojioneemoji" src="http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/1f62c.png">bb<img class="emojioneemoji" src="http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/1f600.png">cc';

$doc = new DOMDocument();
@$doc->loadHTML($url);

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

$str = "" ;
$i=0;
$src_array=array();
foreach ($tags as $tag) {

    $img_path =  $tag->getAttribute('src');
    $src_array[]=$img_path;
    $directory = $img_path;
    $ee = pathinfo($directory);
    $pic_name=  $ee['basename'];
    $next = "" ;
    $previous = "";

    if ($tag->previousSibling && get_class($tag->previousSibling) == "DOMText") {
        $previous = $tag->previousSibling->wholeText . "-" ;
    }
    if($tag->nextSibling && get_class($tag->nextSibling) == "DOMText") {
        $next = $tag->nextSibling->wholeText . "-" ;
    }
    if(isset($previous_tag)){
        $previous="";
    }
    $str .= $previous. $pic_name . "-" . $next ;
    $previous_tag=$tag;
}
$str=rtrim($str,"-");   
echo  $str ;

<强>更新

如果要恢复字符串,可以尝试以下代码,在上面的代码中添加数组$src_array以存储链接src:

echo "<br/>";
$str_array=explode("-",$str); //please pay attention to the splitter character, it should be enough special 
$j=0;
$recover_str="";
for($i=0;$i<count($str_array);$i++)
{
    if(($i%2)==0){
        $recover_str .= $str_array[$i];
    }
    else{
        $recover_str .= '<img class="emojioneemoji" src="'.$src_array[$j].'">';
        $j++;
    }

}
echo  $recover_str ;