0

I have the following that I need removed from string in loop.

<comment>Some comment here</comment>

The result is from a database so the the content inside the comment tag is different.
Thanks for the help.

Figured it out. The following seems to do the trick.

echo preg_replace('~\<comment>.*?\</comment>~', '', $blog->comment);

4
  • 2
    So you want to remove the <comment> tags? Are there any other HTML tags in this string? Commented Jan 12, 2012 at 17:07
  • Do you want to remove the text inside the tags too? Commented Jan 12, 2012 at 17:17
  • Seems like XML to me, so DOM & getELementsByTagName should work pretty much out of the box... Commented Jan 12, 2012 at 17:17
  • Thanks for the reply. Yes I would like to remove both the <comment> and the text inside it. Commented Jan 12, 2012 at 18:32

2 Answers 2

1

This may be overkill, but you can use DOMDocument to parse the string as HTML, then remove the tags.

$str = 'Test 123 <comment>Some comment here</comment> abc 456';
$dom = new DOMDocument;
// Wrap $str in a div, so we can easily extract the HTML from the DOMDocument
@$dom->loadHTML("<div id='string'>$str</div>");  // It yells about <comment> not being valid
$comments = $dom->getElementsByTagName('comment');
foreach($comments as $c){
   $c->parentNode->removeChild($c);
}
$domXPath = new DOMXPath($dom);
// $dom->getElementById requires the HTML be valid, and it's not here
// $dom->saveHTML() adds a DOCTYPE and HTML tag, which we don't need
echo $domXPath->query('//div[@id="string"]')->item(0)->nodeValue; // "Test 123  abc 456"

DEMO: http://codepad.org/wfzsmpAW

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

Comments

1

If this is only a matter of removing the <comment /> tag, a simple preg_replace() or a str_replace() will do:

$input = "<comment>Some comment here</comment>";

// Probably the best method str_replace()
echo str_replace(array("<comment>","</comment>"), "", $input);
// some comment here

// Or by regular expression...    
echo preg_replace("/<\/?comment>/", "", $input);
// some comment here

Or if there are other tags in there and you want to strip out all but a few, use strip_tags() with its optional second parameter to specify allowable tags.

echo strip_tags($input, "<a><p><other_allowed_tag>");

1 Comment

Thanks for the reply. I would like to remove the comment tags and also the text inside.

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.