replace html of tags with php regex
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 ></div>
<div ><span>holding content</span></div>
<img src='http://source.com/to/change' class='identifyingClass3' alt='descrip'/>
_END;
Resulting fileX.php
<?php
echo <<<_END
<div >New content jsd soisvkbsdv</div>
<div >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?
Answer
Solution:
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,
Answer
Solution:
As already stated, RegEx is not recommended for doing such kind of things. Look at this excellent answer. My personal favourite is SimleDom which provides a jQuery-like syntax and makes working with HTML in PHP actually joyful ;).