replace html of tags with php regex

873

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?

388

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,

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

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 ;).

People are also looking for solutions to the problem: php - YouTube data download with cclive & gcap

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.