preg_match表达式,用于在各个HTML标记之间添加换行符

时间:2017-02-14 11:26:33

标签: php html regex

我有一个HTML文件,其中多个HTML标记出现在一行中。例如:

<body class=" yui3-skin-sam controls-visible guest-site signed-out public-page site"> <a href="#main-content" id="skip-to-content">Skip to Content</a> <div id="outer-wrapper"> <div id="wrapper" class="echa-styled live container-fluid"> <div id="content-wrapper"> <a href="#main-content" id="skip-to-content">Skip to Content</a> <header id="banner" role="banner">

我有一个PHP应用程序从该文件中读取,并将其写入(经过一些处理以删除各种标记之后)到另一个文件。但是,在输出文件中,我还想在每个HTML标记之间创建新行"\n"。在上面的示例中,所需的输出是这样的 - 唯一的区别是每个标记的开头在输出文件中的新行开始:

<body class=" yui3-skin-sam controls-visible guest-site signed-out public-page site"> 
<a href="#main-content" id="skip-to-content">Skip to Content</a>
<div id="outer-wrapper">
<div id="wrapper" class="echa-styled live container-fluid">
<div id="content-wrapper">
<a href="#main-content" id="skip-to-content">Skip to Content</a>
<header id="banner" role="banner">

我有一个正则表达式,我已经用它来删除一些preg_replace('/<!--(.|\s)*?-->/', '', $body);

的条件标签

我正在考虑对其进行修改,以便不是定位条件标记(<!-- -->),而是定位<>。然后我将与preg_match

一起使用它

但是我不确定如何构建适当的preg_match条件,特别是在添加新行字符的方式/位置方面。我想第一个参数是'/<(.|\s)*?>/'来定位任何打开/关闭HTML标签。

请有人建议如何执行此操作或是否有其他解决方案可以解决此问题?

4 个答案:

答案 0 :(得分:1)

(<([^> ]+)[^>]*>)(?![^<>]*<\/\2>)

替换为$1\n

<tag properties="values"></tag> =&gt; <tag properties="values"></tag>

<tag properties="values">content</tag> =&gt; <tag properties="values">content</tag>

<tag properties="values"><nested-tag>content</nested-tag></tag> =&gt; <tag properties="values">\n<nested-tag>content</nested-tag\n</tag>

答案 1 :(得分:0)

不确定为什么这篇文章被低估了,因为它是一个完全合法的编程问题。

无论如何,我找到了自己的解决方案就是使用它:

$body = preg_replace('/>/', ">\n", $body);

不知道这是否正确,但我接受它作为答案,因为没有其他人帮助过它,它做了我想做的事。

答案 2 :(得分:0)

试试此代码

$body = '<body class=" yui3-skin-sam controls-visible guest-site signed-out public-page site"> <a href="#main-content" id="skip-to-content">Skip to Content</a> <div id="outer-wrapper"> <div id="wrapper" class="echa-styled live container-fluid"> <div id="content-wrapper"> <a href="#main-content" id="skip-to-content">Skip to Content</a> <header id="banner" role="banner">';

$body = preg_replace("/>/", "> \n", trim($body));

echo $body;

/* output

<body class=" yui3-skin-sam controls-visible guest-site signed-out public-page site"> 
 <a href="#main-content" id="skip-to-content"> 
Skip to Content</a> 
 <div id="outer-wrapper"> 
 <div id="wrapper" class="echa-styled live container-fluid"> 
 <div id="content-wrapper"> 
 <a href="#main-content" id="skip-to-content"> 
Skip to Content</a> 
 <header id="banner" role="banner"> 


*/

答案 3 :(得分:0)

我做的很简单:

$html = preg_replace('/>\s*</', ">\n<", $html);
相关问题