【问题标题】:Remove line breaks in a xml file, in tags and between, keeping the structure删除 xml 文件中、标签中和之间的换行符,保持结构
【发布时间】:2016-04-20 21:44:08
【问题描述】:

长标题:)

无论如何,我有许多 XML 文件希望即时清理,使用 PHP preg_replace RegEx 输出进行简单的即时转换。

现在我不能使更改永久化,所以我编写了一个 php 函数来遍历文件。

我无法修复的是 RegEx 模式。

https://regex101.com/r/bN5eF4/7

我要匹配:

<all-tags with-their="attribute"
even-if-there="are-more">
and all the content between the start and end tag
even if there
are line breaks
in between them
</all-tags>

我敢打赌这很简单,但我从来没有很好地处理过 RegEx……很遗憾。

已编辑

似乎人们希望我构建一个 SimpleXML 的解析器函数,该函数通过 xml 文件并删除换行符?

在同一过程中,我想删除一些元素及其内容,具体取决于其属性中所说的内容。 分析可以这么说。

我认为在使用 Xsltprocessor 处理 xml 文件之前进行换行和分析会是更快的选择?

【问题讨论】:

  • 不要用正则表达式解析 XML;使用真正的 XML 解析器。
  • 为此,RegEx 要快得多,因为我将它作为字符串加载,然后只想删除标签内和标签之间的换行符。
  • 检测您何时在标签内和标签之间不是正则表达式的工作。
  • 那有更好的建议吗?
  • How do you parse and process HTML/XML in PHP?。如果您的尝试失败,请显示minimal reproducible example,您将获得大量帮助。

标签: php regex xml tags preg-replace


【解决方案1】:

我设法用 2 个正则表达式模式做到了。
输入:

<all-tags 
   with-their="attribute"

   even-if-there="are-more"
aa="1">
and all the content between
 the start and end tag
</all-tags>
<meta-tag />

1。在打开标记之前和结束标记之后删除换行符https://regex101.com/r/PPzkWv/2/

/(?<=\>)(\n+)|(\n+)(?=\<)/

输出:

<all-tags 
   with-their="attribute"

   even-if-there="are-more"
aa="1">and all the content between
 the start and end tag</all-tags><meta-tag />

2。从输出中删除标签内的换行符而不破坏语义https://regex101.com/r/GvBc7J/3/

/(\s?\n+\s+|\n)/

最终输出

<all-tags with-their="attribute" even-if-there="are-more" aa="1">and all the content between the start and end tag</all-tags><meta-tag />

【讨论】:

    【解决方案2】:

    尝试以下正则表达式:

    /(?<=\>)(\r?\n)|(\r?\n)(?=\<\/)/
    

    在这里,您正在搜索 &gt; 末尾或 &lt;/ 开头的换行符,并将其替换为空字符串。

    Regex101查看演示

    根据您的示例输入文本,它将删除所有换行符并将内容发出为:

    <all-tags with-their="attribute" even-if-there="are-more">and all the content between the start and end tag</all-tags>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 2013-12-01
      相关资源
      最近更新 更多