【问题标题】:Split HTML string into array based on parent-level elements根据父级元素将 HTML 字符串拆分为数组
【发布时间】:2015-12-31 17:51:39
【问题描述】:

我需要转换 the_content(); 返回的 HTML 字符串;在 Wordpress 中到每个父级元素的数组。例如:

<h3>My subtitle</h3>
<p>Some content here</p>
<blockquote><p>A blockquote goes here</p></blockquote>

会变成:

array['<h3>My subtitle</h3>', '<p>Some content here</p>', '<blockquote> <p>A blockquote goes here</p></blockquote>']

我们要这样做的原因是在内容中插入广告 - 如果第一段或内容块大于 670 个字符,则在第一段之后,如果内容短于该长度,则在第二段之后。挑战在于这些段落中的任何一个是否被另一个元素包裹,或者是否涉及另一个元素。

这是我目前拥有的代码:

$content = apply_filters('the_content', get_the_content());
$content = explode("</p>", $content);
$firstParagraphLength = strlen($content[0]);

if($firstParagraphLength > 670) {
    $paragraphAdAfter = 1;
} else {
    $paragraphAdAfter = 2;
}

// If this is after the target paragraph, insert ad code first
for ($i = 0; $i <count($content); $i++) {
    if ($i == $paragraphAdAfter) { ?>
        <!-- AD CODE -->
        My ad code goes here, great!
    <?php
    }
        echo $content[$i] . "</p>";
} ?>

这确实有效,但如果第一段或第二段中包含块引用,则广告将插入块引用元素中。数据是非常动态的,所以我需要想办法根据父级元素进行拆分,无论它们是块引用、段落、标题等。

【问题讨论】:

  • 您是否考虑过 Shortcode API 以便内容作者可以决定广告的放置位置?
  • 另外,如果您不指定这是插件还是主题,我们将无法在此处提供答案。您可能还想查看wordpress.stackexchange.com,它非常丰富,内容丰富。
  • @Volomike,可以使用核心 PHP 代码。看看吧!
  • @Venkatraman 谢谢,检查一下!有点困惑,但我会试一试

标签: php wordpress


【解决方案1】:

使用DOMDocument试试下面的代码片段

$string = '
<h3>My subtitle</h3>
<p>Some content here</p>
<blockquote><p>A blockquote goes here</p></blockquote>
';

$dom = new DOMDocument;
$dom->loadHTML($string);

foreach($dom->getElementsByTagName('*') as $node)
{
    $array[] = $dom->saveHTML($node);
}

print_r($array);

演示网址:
http://sandbox.onlinephpfunctions.com/code/e382a845f121f8c4a56595f075a9b1d9fee2d2de

【讨论】:

  • 如果我将参数传递给 getElementsByTagName (如“p”),这是有效的,但由于某种原因带有星号,它将整个内容 HTML 视为单个标签作为第一个数组项,然后行为正确然后。不知道为什么,但如果我只是排除第一遍,它就可以正常工作。谢谢!
  • @volomike,希望你对此没问题,如果你有任何问题,请告诉我。
猜你喜欢
  • 1970-01-01
  • 2015-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多