doucongqian6644 2013-11-08 12:53
浏览 60
已采纳

用自己替换出现的img标签/标签,但在给定的字符串中附加一些字符串

i want to replace img tags in a string. Replacing an img tag and add for example an a[href] tag works fine with a dom parser but this won't help me as i have to alter the tags in an existing string of html. I know that altering html with regex isn't a good idea but i can't figure out how to change img tags as whole in a string of html. Beside that i need to wrap the tag in an a[href] where the [href] is provided via a property of the img tag.

<img class="myclasses" width="100" src="mysource" data-image-src="another_src">

After the "transformation" any img tag found should look like this:

<a href="another_src"><img [...] src="http://myexample.me[mysource]"></a>

I got it to work if one image is in the string but failed to handle two images.

I hope someone could help me out :)

  • 写回答

1条回答 默认 最新

  • dousui8263 2013-11-08 14:02
    关注

    You can probably achieve what you need using preg_replace_callback and then looping through the image's attributes in the callback function.

    So for example, given this test string:

    $content= <<<HTML
    <img alt="image-alt-2" src="image-path" style="width: 20px; height: 15px; border: 1px solid red;" title="image-title" data-image-src="another_src" />
        <p>Some other tags. These shouldn\'t be changed<br />Etc.</p>
    <img alt="image-alt-2" src="image-path-2" style="width: 35px; height: 30px;" title="another-image-title" data-image-src="somewhere_else" />
    HTML;
    

    We can then match out the images and call our replacement function:

    $content= preg_replace_callback('/<img ((?:[-a-z]+="[^"]*"\s*)+)\/>/i', 'replaceImage', $content);
    

    For my example I'm just removing the data-image-src attribute and using it to create the link, everything else is left as it was:

    function replaceImage($matches) {
        // matches[0] will contain all the image attributes, need to split
        // those out so we can loop through them
        $submatches= array();
        $donelink= false;
        $count= preg_match_all('/\s*([-a-z]+)="([^"]*)"/i', $matches[1], $submatches, PREG_SET_ORDER);
    
        $result= '<img ';
    
        for($ndx=0;$ndx<sizeof($submatches);$ndx++) {
            if ($submatches[$ndx][1]=='data-image-src') {
                // Found the link attribute, prepend the link to the result
                $result= "<a href=\"{$submatches[$ndx][2]}\">$result";
                $donelink= true; // We've added a link, remember to add the closing </a>
            }
            // You can handle anything else you want to change on an attribute-by-attribute basis here
            else {
                // Something else, just pass it through
                $result.= $submatches[$ndx][0];
            }
        }
    
        return "$result/>".($donelink?'</a>':'');
    }
    

    Running that on the sample content gives:

    <a href="another_src"><img alt="image-alt-2" src="image-path" style="width: 20px; height: 15px; border: 1px solid red;" title="image-title"/></a>
        <p>Some other tags. These shouldn\'t be changed<br />Etc.</p>
    <a href="somewhere_else"><img alt="image-alt-2" src="image-path-2" style="width: 35px; height: 30px;" title="another-image-title"/></a>
    

    Hope that helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器