How can I format this string into formatted code using regex

How can I convert this line:

<user_profil><username>root</username><email> root@foo.bar </email></user_profil> 

into something formatted as:

 <user_profil> <username>root</username> <email> root@foo.bar </email> </user_profil> 

using regex.

Also I don't understand why $doc->saveHTML() (an instance of DOMDocument) returns the result in only one line.

+6
source share
2 answers

Actually using regex will be longer. Use more likely

 $doc->preserveWhiteSpace = false; $doc->formatOutput = true; $xml_string = $doc->saveXML(); echo $xml_string; 

This will give you formatted code.

+12
source

Using the @georoot method is better, but if you want to try the regex, you can do it like this:

 (\s+)(\<\w+\>)(\<\w+\>\w+\<\/\w+\>)(\<\w+\>[\w\@\.]+\<\/\w+\>)(\<\/\w+\>) 

Replaced by:

 $2\n\t$3\n\t$4\n$5 

Demo: https://regex101.com/r/QtVCoY/1

+5
source

Source: https://habr.com/ru/post/1012491/


All Articles