更新:
我在这样的文本中有多个字符串:
<p>[code]</p>
<p> [code] </p>
<p> [code]</p>
<p>[code] </p>
<p> [code]<br /> </p>
在[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代码不再有效,因为新插入的代码被段落包围。
我想从我的数组中删除这些,但只删除占位符周围的段落。
如何在不影响其他文本行中的段落标记的情况下有效地做到这一点?
您可以在原始HTML上使用str_replace
来删除<p>
标记:
$noTagsCntnt = str_replace( array("<p>[", "]</p>"), array("[", "]"), $cntnt );
$_parts = preg_split('/('[.*?'])/', $noTagsCntnt, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)
编辑
如果你确定在短代码之前有一个打开的<p>
标签,你可以尝试在它之前关闭<p>
$noTagsCntnt = str_replace( array("[", "]"), array("</p>[", "]<p>"), $cntnt );
然后CSS以避免空<p>
标签中的多余空白:
p:empty { padding: 0; margin: 0 }
编辑
请参阅CKEditor错误
您不需要使用preg_split,使用preg_replace更容易:
$pattern = '~(<p>)?'[youtube:([^]]+)](?(1)</p>)~';
$replacement = '<iframe width="425" height="344" src="http://www.youtube.com/embed/$2?fs=1" frameborder="0" allowFullScreen=""></iframe>';
$html = preg_replace($pattern, $replacement, $html);