Use preg_replace on condition

Asked

Viewed 70 times

0

I have the following string, which can be the representation of an HTML or XML, makes no difference:

<node1>
    <node2>Conteudo exemplo</node2>
    <node3>Conteudo exemplo</node3>
    <node4>Conteudo exemplo</node4>
    <node5>
        <node6>Conteudo exemplo</node6>
    </node5>
</node1>

I need to create a Pattern to the preg_replace can replace occurrences of > which are not followed by the character <, or only the characters will be replaced > representing the closing of a tag without child nodes in the above example.

I am aware that there are better ways to manipulate documents with this structure, for example using the Class Domdocument, but in that case I really need to use the preg_replace.

Simulating an expected result, replacing the character > for @:

<node1>
    <node2@Conteudo exemplo</node2>
    <node3@Conteudo exemplo</node3>
    <node4@Conteudo exemplo</node4>
    <node5>
        <node6@Conteudo exemplo</node6>
    </node5>
</node1>
  • 1

    Can you put the expected result? For me it was not clear what would be removed from string in this example.

  • @Andersoncarloswoss I put a simulation of the expected result.

  • I think he meant the following, remove "<" and ">" from the content, without changing the tags.

  • 1

    @Wictorchaves Actually the key issue is the implementation of a condition when running preg_replace. In this case I need to replace the characters ">" that do not follow the character "<".

1 answer

2


I do not know if it is the best solution, but try to do so in PHP:

preg_replace('/>(.*?)</', '@$1<', $XML_HTML);
  • Great, produced the expected result. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.