Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Strings - Remove a HTML tag with a specific class, including its contents

I have a string like this:

<div class="container">
  <h3 class="hdr"> Text </h3>
  <div class="main">
    text
    <h3> text... </h3>
    ....

  </div>
</div>

how do I remove the H3 tag with the .hdr class using as little code as possible ?

like image 501
Alex Avatar asked Jun 30 '10 13:06

Alex


People also ask

How do I remove a specific HTML tag from a string in PHP?

PHP provides an inbuilt function to remove the HTML tags from the data. The strip_tags() function is an inbuilt function in PHP that removes the strings form HTML, XML and PHP tags. It accepts two parameters. This function returns a string with all NULL bytes, HTML, and PHP tags stripped from a given $str.

How do I remove a tag from a string?

The HTML tags can be removed from a given string by using replaceAll() method of String class. We can remove the HTML tags from a given string by using a regular expression. After removing the HTML tags from a string, it will return a string as normal text.

Which function is used to remove all HTML tags from string?

The strip_tags() function strips a string from HTML, XML, and PHP tags. Note: HTML comments are always stripped.

How do you remove a tag in CSS?

By setting the text-decoration to none to remove the underline from anchor tag. Syntax: text-decoration: none; Example 1: This example sets the text-decoration property to none.


2 Answers

Using as little code as possible? Shortest code isn't necessarily best. However, if your HTML h3 tag always looks like that, this should suffice:

$html = preg_replace('#<h3 class="hdr">(.*?)</h3>#', '', $html);

Generally speaking, using regex for parsing HTML isn't a particularly good idea though.

like image 153
Daniel Egeberg Avatar answered Sep 28 '22 06:09

Daniel Egeberg


Something like this is what you're looking for...

$output = preg_replace("#<h3 class=\"hdr\">(.*?)</h3>#is", "", $input);

Use "is" at the end of the regex because it will cause it to be case insensitive which is more flexible.

like image 20
Webnet Avatar answered Sep 28 '22 05:09

Webnet