【问题标题】:Regexp for fix broken HTML tags用于修复损坏的 HTML 标签的正则表达式
【发布时间】:2022-01-19 13:13:58
【问题描述】:

我损坏了 HTML 标签,例如:

$page = "some text <p/ another text <br/ some text <br/ and/or another text";

我需要将其修复为正常&lt;br&gt; &lt;p&gt;

我正在尝试这个:$page = preg_replace('/(\&lt;(.+?)\/)/i', '&lt;\2&gt;', $page);

但它不起作用

我为第 2 组使用了名称“标签”: $page = preg_replace('/(\&lt;(?&lt;tag&gt;.+?)\/)/i', '\k&lt;tag&gt;', $page);

但它也不起作用。

我哪里错了?请帮帮我。

I simplified the example for clarity in the form of html. In fact, there are not only tags present there, there are words such as the names of cities, streets and other data, and all of them cannot be provided for a simple replacement

我在这里检查过。看起来不错,但是在php上我没有结果 https://regex101.com/r/t1JmJP/1

【问题讨论】:

  • 为什么是正则表达式,为什么不简单的字符串替换? 3v4l.org/6dL9I
  • 我正在学习正则表达式
  • 字符串替换示例错误地替换了有效的 void 元素,例如 &lt;br/&gt; - 它返回 &lt;br&gt;&gt;
  • @A__ 是的,但我们没有得到一个实际包含其中任何一个的示例。这可能似乎是一个自然要求,但不提它,我会说这个问题相当不完整。
  • “我正在尝试这个:[...] 但它不起作用” - 你在说什么? 3v4l.org/XooSo - 那么究竟是什么在这里不起作用?

标签: php regex


【解决方案1】:

您的初始代码运行良好:

<?php

$page = "some text <p/ another text <br/ some text <br/ and/or another text";
$page = preg_replace('/(\<(.+?)\/)/i', '<\2>', $page);
echo $page;

当您从 CLI 运行它时:

$ php test.php
some text <p> another text <br> some text <br> and/or another text

请参阅此 regex101:https://regex101.com/r/9JtCxP/1。 与您的链接不同的是,我点击了左侧菜单上的“替换”并添加了“g”标志。

【讨论】:

    【解决方案2】:

    错误的原因是在文本中,而不是&lt;&gt;,而是&amp;lt;&amp;gt;。视觉上没有区别。但只是视觉上的。

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      相关资源
      最近更新 更多