我如何使用正则表达式将此行格式化为格式化代码

时间:2022-06-25 20:43:50

How I can convert this line :

我如何转换这一行:

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

into something formatted like :

进入格式化为:

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

using regex.

使用正则表达式。

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

另外我不明白为什么$ doc-> saveHTML()(DOMDocument的一个实例)只将结果作为一行返回。

2 个解决方案

#1


12  

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.

这应该为您提供格式化的代码。

#2


5  

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

使用@georoot方式更好,但如果你想尝试正则表达式,你可以这样做:

(\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

演示:https://regex101.com/r/QtVCoY/1

#1


12  

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.

这应该为您提供格式化的代码。

#2


5  

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

使用@georoot方式更好,但如果你想尝试正则表达式,你可以这样做:

(\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

演示:https://regex101.com/r/QtVCoY/1