1

How can the <title> element be deleted inside this XML string?

$input=
'<items>dfd jdh flkdjf 
<title>My Test Title
</title>....
<store>my store 1</store>
</items>.....';

$output=
    '<items>dfd jdh flkdjf 
        ....
    <store>my store 1</store>
    </items>.....';

Thanks

Gumbo
  • 643,351
  • 109
  • 780
  • 844
Ben
  • 25,389
  • 34
  • 109
  • 165
  • 2
    ["Have you tried using an XML parser instead?" says the wise man bobince](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – BoltClock Dec 12 '10 at 18:09
  • ok, how you doing it with xmldocument?Its for unit test not for production soo regex can be good also – Ben Dec 12 '10 at 18:10
  • @BoltClock: That depends on the XML document. – Gumbo Dec 12 '10 at 18:10

2 Answers2

7

Simplexml

$str = '<items>1<title>lalala</title><others>...</others></items>';
$xml = simplexml_load_string($str);
unset($xml->children()->title);
$output = str_replace("<?xml version=\"1.0\"?>\n", '', $xml->asXml());
ajreal
  • 46,720
  • 11
  • 89
  • 119
2

If you are working with unknown input data, or with production code, you should use an XML parser.

If you're working in test environment and the input data is known:

$output = preg_replace('%<title>[^<]*</title>%', '', $input);

If you need to allow for attributes on the tag, I suggest using a real XML parser, for maximum reliability and minimum chance of error.

Mike Clark
  • 10,027
  • 3
  • 40
  • 54