2

I wonder if there is any way to remove a specific tags from a php string?

I have knowledge of several features that make it, for example strip_tags, but what I really want is to remove tags containing the class attribute or any, I give an example below:

$string = '<p>Test paragraph.<p class="inner">Here is some inner text</p></p>';

How I can remove only the tag containing the class attribute 'inner'?

If anyone can tell me a way to do this, I'd be grateful.

3
  • 2
    You'll need to parse the HTML yourself. Commented Nov 29, 2012 at 16:22
  • Use a DOM parser to parse your HTML, then modify the DOM and recreate the HTML from the DOM. Look at the PHP DOM page. This is not a problem you want to solve with regular expressions. Commented Nov 29, 2012 at 16:22
  • I've asked a similar doubt.This link has the answer. Commented Nov 29, 2012 at 16:25

2 Answers 2

2

There's no function to do that, and to avoid using a horrible regular expression the best way would be to load it into a DOMDocument class and iterate over the tags in the string. You can then selectively remove tags depending on the class attribute and then write it back out to a string.

See http://php.net/manual/en/class.domdocument.php for the documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

@evolquez: No need for iteration. Check my answer.
1

Quite simple with XPath:

<?php

$string = '<p>Test paragraph.<p class="inner">Here is some inner text</p></p>';

$dom = new DOMDocument;
@$dom->loadXML($string);

$xpath = new DOMXPath($dom);

$inners = $xpath->query('//p[@class="inner"]'); //Select all p.inner in the document

foreach ($inners as $element) {
    $element->parentNode->removeChild($element); //Remove 'em
}

var_dump($dom->saveHTML($dom));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.