dongzhong5573 2013-07-09 17:51
浏览 71
已采纳

如何在PHP中使用正则表达式替换HTML中的ALT和TITLE文本

I have a html content as listed below.

<img title="" style="float: none;margin-right: 10px;margin-top: 10px;margin-bottom: 10px;" src="http://www.mbatious.com/sites/default/files/imagecache/Large/Distchart.jpg" class="imagecache-Large" alt="">

I would like to replace the empty alt and title text with the name of the image file (Distchart). How to do this using preg_replace in php? After performing replace operation, the html should be like

<img title="Distchart" style="float: none;margin-right: 10px;margin-top: 10px;margin-bottom: 10px;" src="http://www.mbatious.com/sites/default/files/imagecache/Large/Distchart.jpg" class="imagecache-Large" alt="Distchart">
  • 写回答

3条回答 默认 最新

  • dpkrbe395930 2013-07-09 18:15
    关注

    As Maxim Kumpan suggests it, the best way is to use the dom:

    $doc = new DOMDocument();
    @$doc->loadHTML($html);
    $imgs = $doc->getElementsByTagName('img');
    foreach($imgs as $img) {
        if (preg_match('~[^/]+(?=\.(?>gif|png|jpe?+g)$)~i', $img->getAttribute('src'), $match)) {
            $name = $match[0];
            if ($img->getAttribute('alt')=='') $img->setAttribute('alt', $name);
            if ($img->getAttribute('title')=='') $img->setAttribute('title', $name);
        }
    }
    $result = $doc->saveHTML();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥15 第一个已完成,求第二个做法
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?