【发布时间】:2013-12-07 13:45:37
【问题描述】:
更新:
我在这样的文本中有多个字符串:
<p>[code]</p>
<p> [code] </p>
<p> [code]</p>
<p>[code] </p>
<p> [code]<br /> </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