【问题标题】:PHP DOM remove (parent) tagsPHP DOM 移除(父)标签
【发布时间】:2013-12-07 13:45:37
【问题描述】:

更新:

我在这样的文本中有多个字符串:

<p>[code]</p>
<p>&nbsp;[code]&nbsp;&nbsp;</p>
<p>&nbsp;[code]</p>
<p>[code]&nbsp;</p>
<p>&nbsp;[code]<br />&nbsp;</p>

在 [code] 的情况下,我想删除周围的段落、空格和换行符(如果可能)。只有 [code] 必须生存。

我该怎么做?

老例子:

我有这个在 CKeditor 中生成的 HTML:

<p>This is a line of text.</p>
<p>[youtube:youtubId]</p>
<p>This is a line of text.</p>
<p>[youtube:youtubId]</p>
<p>This is a line of text.</p>
<p>[youtube:youtubId]</p>
<p>This is a line of text.</p>

在我的 CMS 中,我使用方括号来定义插件。这些代码被 PHP 代码替换,在本例中是一个显示 youtube 缩略图的小脚本,可单击以在灯箱中查看电影。当然还有更多种类的插件。

我所做的是从这些 HTML 创建一个数组:

$_parts = preg_split('/(\[.*?\])/', $cntnt, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)

这给了我:

array (size=7)
  0 => string '<p>This is a line of text.</p>  <p>' (length=35)
  1 => string '[youtube:youtubeId]' (length=19)
  2 => string '</p>  <p>This is a line of text.</p>  <p>' (length=41)
  3 => string '[youtube:youtubeId]' (length=19)
  4 => string '</p>  <p>This is a line of text.</p>  <p>' (length=41)
  5 => string '[youtube:youtubeId]' (length=19)
  6 => string '</p>  <p>This is a line of text.</p>' (length=36)

当我用包含 div 或 iframe 的代码替换占位符 [youtube:youtubId] 时,HTML 代码不再有效,因为新插入的代码被段落包围。

我想从我的数组中删除这些,但只删除占位符周围的段落。

如何在不影响其他文本行中的段落标签的情况下有效地做到这一点?

【问题讨论】:

  • 你为什么关心它周围的东西?只需将符合您的规则的内容替换为 youtube 链接/灯箱等即可。
  • 在 p(aragraphs) 中放置 DIV 或 iFrame 不是 HTML 有效的。

标签: php arrays dom preg-replace


【解决方案1】:

您可以在原始 HTML 上通过str_replace 去除&lt;p&gt; 标签:

$noTagsCntnt = str_replace( array("<p>[", "]</p>"), array("[", "]"), $cntnt );
$_parts = preg_split('/(\[.*?\])/', $noTagsCntnt, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)

编辑

如果您确定在它之前有一个打开的&lt;p&gt; 标签,您可以尝试在短代码之前关闭&lt;p&gt;

$noTagsCntnt = str_replace( array("[", "]"), array("</p>[", "]<p>"), $cntnt );

然后用 CSS 来避免空 &lt;p&gt; 标签中的多余空格:

p:empty { padding: 0; margin: 0 }

编辑

CKEditor bug

【讨论】:

  • 这可行,感谢您的反馈,但是当括号之前或之后有空格或其他字符时再次中断。
  • 感谢您的更新,但它给解决方案增加了一个问题,然后解决了。我认为必须有一种更有效的方式。
【解决方案2】:

你不需要使用preg_split,使用preg_replace更容易:

$pattern = '~(<p>)?\[youtube:([^]]+)](?(1)</p>)~';
$replacement = '<iframe width="425" height="344" src="http://www.youtube.com/embed/$2?fs=1&quot; frameborder="0" allowFullScreen=""></iframe>';
$html = preg_replace($pattern, $replacement, $html);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 2017-06-11
    • 2015-09-27
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多