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

替换<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 滑块验证码移动速度不一致问题
  • ¥15 定制ai直播实时换脸软件
  • ¥100 栈回溯相关,模块加载后KiExceptionDispatch无法正常回溯了
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中