dsxpt62448 2016-03-29 03:22
浏览 59

如何获取img标签而不用DOMDocument :: saveHTML从字符串中更改它?

I have string like:

...。すっきりと整理され...のです。<br /><br /><img src="/photo/images/2016/03/25/0_3316.jpg" alt="漢字漢字漢字" /><br /><br />「あのと...

And I'm trying to get img tag by DOMDocument::saveHTML:

$topic_conv = mb_convert_encoding(htmlspecialchars_decode($topic['Topic']['body']), 'HTML-ENTITIES', 'UTF-8');
$doc->loadHTML($topic_conv);
$img_tags = $doc->getElementsByTagName('img');
foreach ($img_tags as $tag) {
    $img_alt = $tag->getAttribute('alt');
    if (empty($img_alt)) continue;
    $img = $doc->saveHTML($tag);
    var_dump($img);
    str_replace($img, $img . "<span style='{$img_style_caption}'>" . $img_alt . "</span>", htmlspecialchars_decode($topic['Topic']['body'])));
}

The output is: <img src="/photo/images/2016/03/25/0_3316.jpg" alt="漢字漢字漢字">

It's different from the original string - there is no SPACE and / before the closing bracket, it should have /> instead of just >. And my next line of code str_replace doesn't work, because it doesn't match.

Maybe, someone know how can I get img tag as it is in the original string?

  • 写回答

1条回答 默认 最新

  • dtu72460 2016-03-30 22:32
    关注

    If you still need it, then try like this:

    str_replace($img, $img . "<span style='{$img_style_caption}'>" . $img_alt . " /" . "</span>", htmlspecialchars_decode($topic['Topic']['body'])));
    

    PS: code is from my head (so is untested). Let me know if any issues...

    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线