regex to wrap img tag with href containg the src

后端 未结 3 1099
别跟我提以往
别跟我提以往 2021-01-27 12:38

[Edited - Sorry Bart] I\'ve looked at other answers but struggling to match this. I want to wrap an image tag where the src is the second attribute (after title) with a specific

相关标签:
3条回答
  • 2021-01-27 13:03

    Try this :

    $newString = preg_replace('`<img([^>]*)src="\\.\\./\\.\\./images/([^"]+)"([^>])*>`','<a href="event:images/expand/$2"><img$1src="images/$2"$3></a>', $oldString);
    

    Limitations are :

    • It will apply the changes in things like <input value='<img src="../../images/test.jpg/>"'/>
    • If " are replaced by ' in your img tags, you'll have to change the regexp
    • It will choke on things like <img alt="6>5" src="../../images/test.png"/>

    I agree with other commenters saying regexp are bad to parse HTML. But there's almost no parsing here and the format of things to replace seems to be under control (generated by tinymce).

    0 讨论(0)
  • 2021-01-27 13:04

    Similar questions have been answered several times and the answer is always the same: do not use regular expressions to tamper with HTML. In PHP, you can use XPath and the SimpleXml or DOMParser extensions to solve this problem.

    Sorry for posting so many links to my own answers but the answers themselves and the questions they are answering contain a lot of information on the subject.

    0 讨论(0)
  • 2021-01-27 13:19

    Try this code:

    <?php
    $str = '<img title="who_main_Layer_1.jpg" src="../../images/who_main_Layer_1.jpg" alt="who_main_Layer_1.jpg" width="380" height="268" />';
    
    preg_match('#src="(?:.*/)?(.*?)"#', $str, $match);
    $src = $match[1];
    ?>
    <a href="event:images/expand/<?php echo $src; ?>"><img src=”images/<?php echo $src; ?>” /></a>
    

    EDIT: another version to account for multiple tags in the string:

    $replace = '<a href="event:images/expand/$1"><img src="images/$1" /></a>';
    $str = preg_replace('#<\s*img.*?src="(?:[^"]+/)?(.*?)".*?>#s', $replace, $str);
    
    0 讨论(0)
提交回复
热议问题