Skip to content
Advertisement

How to replace custom html tag with html code in php

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:

JavaScript

I need to find the custom tags and replace them with the template of the item, as a result:

JavaScript

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:

JavaScript

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:

JavaScript

If you don’t “have” the HTML, then you can use ob_start() and ob_get_clean().

JavaScript

I haven’t tested this, just did it on top of my head. So there might be some typos!

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement