duanpin9531 2012-11-13 22:29
浏览 28

用php regex替换标签的html

I have a situation in which I think I may have to use regex to alter html tag content or src based on the class attribute.

To document I will be parsing will be either nicely formed html, partial html or php files.

EG I would need to change/fill these tags with inner content: fileX.php

<?php
echo <<<_END
<div class="identifyingClass1"></div>
<div class="identifyingClass2"><span>holding content</span></div>
<img src='http://source.com/to/change' class='identifyingClass3' alt='descrip'/>
_END;

Resulting fileX.php

<?php
echo <<<_END
<div class="identifyingClass1">New content jsd soisvkbsdv</div>
<div class="identifyingClass2">More new content</div>
<img src='new/source.tiff' class='identifyingClass3' alt='descrip'/>
_END;

The html could be complete, could be separated by php, be as is, be inside a hereDOC...

Is the best way to achieve this to just use regex or has anyone seen or used a class for this kind of thing?

  • 写回答

2条回答 默认 最新

  • douba9425 2012-11-13 22:37
    关注

    Regex is evil for such case. Better you work on the generated html. Here's how you do it.

    Enable output buffering. On the ob_start function add your own callback. Process the generated html with DOMDocument inside the handler. Something like this,

    function my_handler($contents){
         $doc = DOMDocument::loadHTML ($contents);
         // change your document here and return it later
         return $doc->saveHTML();
    }
    ob_start('my_handler');
    
    评论

报告相同问题?