This is my scenario: In a custom CMS developed in PHP, I need to parse HTML string searching some custom tags to replace them with some HTML code. Here is an example for clarifying:
<h2>Some Title</h2> <p>Some text</p> [[prod_id=123]] [[prod_id=165]] // custom tag <p>More text</p>
I need to find the custom tags and replace them with the template of the item, as a result:
<h2>Some Title</h2> <p>Some text</p> <!--Start Product123--> <p>Title Product 123</p> <!--End Product123--> <!--Start Product165--> <p>Title Product 165</p> <!--End Product165--> <p>More text</p>
This would be very helpful, but I need to do something else, I need to detect blocks of tags and add some code before – after the tags, but only once per block of tags. In this example, the final code needed would be something like:
<h2>Some Title</h2> <p>Some text</p> <div><!-- Here the start of the block --> <!--Start Product123--> <p>Title Product 123</p> <!--End Product123--> <!--Start Product165--> <p>Title Product 165</p> <!--End Product165--> </div><!-- Here the end of the block --> <p>More text</p>
The perfect solution for me would be a function with the original HTML code as argument, and returning the final html code. Any help is appreciated.
Advertisement
Answer
I will advise you to not use Regex along with HTML, this can result in a lot of problems. Instead do something like where you store the text/content of articles and then only process that.
But for the sake of completeness, you can use something like this:
$html = preg_replace_callback("/[[prod_id=(d+)]]/", function($matches) { $prod_id = $matches[1]; return '<p>Title Product ' . $prod_id . '</p>'; }, $html); // where $html is the html you want to process
If you don’t “have” the HTML, then you can use ob_start()
and ob_get_clean()
.
ob_start(); ?> <h2>Some Title</h2> <p>Some text</p> [[prod_id=123]] [[prod_id=165]] // custom tag <p>More text</p> <?php $html = ob_get_clean(); // do the regex_replace_callback here
I haven’t tested this, just did it on top of my head. So there might be some typos!