duanji9481 2017-06-07 10:41
浏览 298
已采纳

替换<img>标记上的空alt标记

I would like to replace my empty alt tags on images in a string. I have a string that contains all the text for a curtain page. In the text are also images, and a lot of them have empty tags (old data), but most of the time they do have title tags. For example: <img src="assets/img/test.png" alt="" title="I'am a title tag" width="100" height="100" />

What I wish to have: <img src="assets/img/test.png" alt="" title="I'am a title tag" alt="I'am a title tag" width="100" height="100" />

So: I need to find all the images in my string, loop trough the images, find title tags, find alt tags, and replace the empty alt tags with the title tags that do have a value.

This is what i tried:

preg_match_all('/<img[^>]+>/i',$return, $text);
if(isset($text)) {
            foreach( $text as $itemImg ) {
                foreach( $itemImg as $item ) {
                    $array = array();
                    preg_match( '/title="([^"]*)"/i', $item, $array );
                    if(isset($array[1])) {
                        //So $array[1] is a title tag, now what?
                    }
                }

            }
        }

I don't know have to complete the code, and I think there must be a easier fix for this. Suggestions?

  • 写回答

5条回答 默认 最新

  • doujiao1180 2017-06-07 10:55
    关注

    Using Regex is not a good approach you should use DOMDocument for parsing HTML. Here we are querying on those elements whose alt attribute is empty which is actually asked in question.

    Try this code snippet here

    <?php
    
    ini_set('display_errors', 1);
    
    $string=<<<HTML
    <img src="assets/img/test1.png" alt="" title="I'am a title tag" width="100" height="100" />
    <img src="assets/img/test2.png" alt="" title="I'am a title tag" width="100" height="100" />
    <img src="assets/img/test3.png" alt="" title="I'am a title tag" width="100" height="100" /> 
    HTML;
    
    $domDocument = new DOMDocument();
    $domDocument->loadHTML($string,LIBXML_HTML_NODEFDTD);
    
    $domXPath = new DOMXPath($domDocument);
    $results = $domXPath->query('//img[@alt=""]');
    foreach($results as $result)
    {
        $title=$result->getAttribute("title");
        $result->setAttribute("alt",$title);
        echo $domDocument->saveHTML($result);
        echo PHP_EOL;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行