【问题标题】:Filter html content by type of element in PHP在 PHP 中按元素类型过滤 html 内容
【发布时间】:2018-12-07 18:17:15
【问题描述】:

假设我有一个包含 html 的变量:

<?php 
$content = "<h3>Transition movement</h3><p>It's fun and will make you more resilient.</p>";
?>

我可以“过滤”它,以便我可以在某处呼应标题并在其他地方呼应段落,如下所示?

<div class="big-purple"><?php echo $content_title; ?></div>
<div class="side-bar"><?php echo $content_paragraph; ?></div>

有点像我会使用 javascript 访问 DOM 元素,仅在服务器端在它被加载到页面上之前。我问这个是因为我从 Wordpress 中的单个富文本字段中获取内容,并且我必须将内容放在前端布局的不同部分。

【问题讨论】:

  • PHP 还有一个 DOM 扩展:php.net/dom
  • DOMDocument 可以提供帮助,但前提是您的 HTML 有效
  • 我最终没有使用 DOM,因为 treyBake 的回答已经足够了。

标签: php html dom


【解决方案1】:

你可以这样做:

<?php
    $content = '<h3>Transition movement</h3><p>It\'s fun and will make you more resilient.</p>';

    preg_match_all(
        '/\<\w[^<>]*?\>([^<>]+?\<\/\w+?\>)?|\<\/\w+?\>/i',
        $content,
        $matches
    );

    $html = $matches[0];

    $heading = $html[0];
    $p = $html[1];
?>

<div><?php echo $heading; ?></div>
<div><?php echo $p; ?></div>

preg_match 将匹配所有&lt; whatever html tag &gt; 并将其分解为一个数组。它将它存储在第一个索引中(因此$html = $matches[0]),所以只需使用它,然后单独获取标签。

您喜欢的潜在奖励积分。

function getHtmlTags($html)
{
    preg_match_all(
        '/\<\w[^<>]*?\>([^<>]+?\<\/\w+?\>)?|\<\/\w+?\>/i',
        $html,
        $matches
    );

    return $matches[0];
}

$html = getHtmlTags($content);

【讨论】:

    【解决方案2】:

    怎么样

    $content = explode("</h3>", "<h3>Transition movement</h3><p>It's fun and will make you more resilient.</p>");//Split at end of h3

    还有:

    <div class="big-purple"><?php echo $content[0]; ?></div>
    <div class="side-bar"><?php echo $content[1]; ?></div>
    

    我不建议这样编码,但如果你想要的话,它可以工作。

    【讨论】:

    • 如果你不推荐它 - 为什么推荐它?
    • 因为在我看来,回答比保持喊叫好。只要它有效,它就不会愚蠢,对吧?
    • 我宁愿编写最高效且能正确使用 PHP 的代码
    【解决方案3】:

    如果我想这样做,我会使用更多变量:

    <?php 
       $headline = "<h3>Transition movement</h3>";
       $paragraph = "<p>It's fun and will make you more resilient.</p>";
       $fullContent = $headline . $paragraph;
    ?>
    

    及以后:

    <div class="big-purple"><?php echo $headline; ?></div>
    <div class="side-bar"><?php echo $paragraph; ?></div>
    

    如果您不能将其保存在两个变量中,请先将其拆分,但可读性要差得多:

    $content = explode("</h3>", "<h3>Transition movement</h3><p>It's fun and will make you more resilient.</p>");
    

    【讨论】:

    • 我不能这样做,因为我将整个 html 内容放在一个字符串中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多