Writing regular expression in PHP to wrap <img> with <a>

This question already has an answer here:

  • RegEx match open tags except XHTML self-contained tags 35 answers

  • preg_replace("{<imgs*(.*?)src=('.*?'|".*?"|[^s]+)(.*?)s*/?>}ims", '<a href=$2><img $1src=$2 $3/></a>', $str)

    handles all non-practical cases

    替代文字


    My I recommend the PHP DOM with loadHTML() instead of regex?

    http://php.net/dom

    http://php.net/domdocument.loadhtml


    May I recommend using jQuery and use this snippet instead, it should be easier (and we all love jQuery to brute-force any problem ;] )

    $('img').wrap( function(){ return '<a href="' + this.src + '"></a>'; });
    

    or is it

    $('img').wrap( function(){ return '<a href="' + $(this).attr('src') + '"></a>'; });
    

    Anyways, fun times to be had, using jQuery to manipulate the DOM clientside ;)

    链接地址: http://www.djcxy.com/p/76844.html

    上一篇: 用正则表达式在Python中解析XML

    下一篇: 在PHP中编写正则表达式以<a>包装<img>