-1

I have a config.ini file formed as XML like that :

<positions>

    <position>
        <name>BLOCK TAB 1</name>
        <tag>[BLOCK_TAB_1]</tag>
    </position>


    <position>
        <name>PERSONALAREA</name>
        <tag>[PERSONALAREA]</tag>
    </position>
</positions>

I tried to remove the block :

<position>
    <name>BLOCK TAB 1</name>
    <tag>[BLOCK_TAB_1]</tag>
</position>

by using preg_replace

$find1 = "/<name>BLOCK TAB 1<\/name>/";
$find2 = "/<tag>\[BLOCK_TAB_1\]<\/tag>/";

$contents = preg_replace($find1, "", $contents);
$contents = preg_replace($find2, "", $contents);

But the content will be

<positions>

    <position>


    </position>


    <position>
        <name>PERSONALAREA</name>
        <tag>[PERSONALAREA]</tag>
    </position>
</positions>

The empty <position> tag ( with tabs inside ) still here.

Try to use /<position[^>]*><\\/position[^>]*>/ to replace empty <position> tag, but because of tabs inside, so replace is not working.

Somebody have idea ?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150

1 Answers1

3

You shouldn't use regex to parse this XML. In this example, you could use XPath to easily identify the <name> that has the text "BLOCK TAB 1", then select its parent and remove it:

$doc = new DOMDocument;
$doc->loadXML($xml);

$xpath = new DOMXpath($doc);

$positions = $xpath->query('//name[text()="BLOCK TAB 1"]/parent::position');

foreach ($positions as $position) {
    // Remove it
    $position->parentNode->removeChild($position);
}

echo $doc->saveXML();

Example

Community
  • 1
  • 1
scrowler
  • 24,273
  • 9
  • 60
  • 92