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

替换<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条)

报告相同问题?