When you want to render web page content based on the specific condition, the content needs to be loaded dynamically. In that case, you need to add or remove HTML element from the web page content. You can easily remove HTML element or tag with class or id using PHP.
The preg_replace() function in PHP, perform a search by regular expression and replace matches. You can remove HTML element by class or id using preg_replace() in PHP. In the example code snippets, we will show you how to remove HTML element with class or id using PHP.
For example, the HTML element needs to be removed from the following HTML.
$html = '<div class="container">
<div id="wrapper">
<h1 class="ttl">Welcome to CodexWorld</h1>
<div id="desc">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
</div>
</div>';
Remove HTML Element with Class
The following code will remove HTML tags (<h1>) with class and the content between this HTML tags using PHP.
$html = preg_replace('#<h1 class="ttl">(.*?)</h1>#', '', $html);
Remove HTML Element by ID
The following code will remove HTML div by ID and the content between this HTML element (<div>) using PHP.
$html = preg_replace('#<div id="desc">(.*?)</div>#', '', $html);