PHP, preg_replace, replace tag with tag attr

后端 未结 2 1536
谎友^
谎友^ 2021-01-27 06:09

Can I have a detail explain about how can I replace with tag with current attr using php?

I read manual and some referencs

How to use php preg_replace to replac

相关标签:
2条回答
  • 2021-01-27 06:34

    It is almost never a good idea to use regular expressions for HTML. Consider DOM, then something like:

    foreach($dom->getElementsByTagName('script') as $script) {
        $temp = $dom->createElement('temp');
        /*
         * create src attribute, append it to $temp and copy value from $script
         * I leave that up to you.
         */
        $script->parentNode->replaceChild($temp, $script);
    }
    
    0 讨论(0)
  • 2021-01-27 06:56

    You need to learn about regular expressions, this site is a useful resource;

    A quick example with preg_replace could be something like this - it could be improved, but hopefully will give you the idea...

    <?php
    $string = '<script src="core.js"></script>';
    $pattern = '/<script src\s?=\s?['|"](.*)['|"]><\/script>/i';
    $replace = ' <temp src="library/js/$1"></temp>';
    $result = echo preg_replace($pattern, $replace, $string);
    ?>
    

    You will need to learn about back-references in order to use matched bits of the string to create your new one. Briefly, the part of your pattern that is wrapped in parenthesis can be retrieved later with the $1 token which you include in your $replace string. You can back-reference as many times as you want this way. You can test regular expressions as you are working on them here too, hope this helps.

    0 讨论(0)
提交回复
热议问题