Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can format this line into formatted code using regex

How I can convert this line :

        <user_profil><username>root</username><email>[email protected]</email></user_profil>

into something formatted like :

<user_profil>
    <username>root</username>
    <email>[email protected]</email>
</user_profil>

using regex.

Also I dont understand why $doc->saveHTML() (an instance of DOMDocument) return the result as one line only.

like image 815
flydev Avatar asked Nov 19 '16 23:11

flydev


2 Answers

Actually using regex would be the longer option. Rather use

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

This should get you the formatted code.

like image 87
georoot Avatar answered Oct 07 '22 20:10

georoot


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

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

Replace with:

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

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

like image 22
Ibrahim Avatar answered Oct 07 '22 20:10

Ibrahim