使用 preg_match_all 过滤提要标题

filter feed titles with preg_match_all

请帮我解决这个问题:)

我有这段代码可以过滤提要标题。然而,这是一个混乱的无序列表。

$countItem = 0;
foreach ($feed->get_items() as $item): {
  $checktitle = $item->get_permalink();
  $keyword_one = '/keyword1/';
  $keyword_two = '/keyword2/';
  if (preg_match_all($keyword_one, $checktitle, $matches) && preg_match_all($keyword_two, $checktitle, $matches)) {
     echo $item->get_title();
  }
}
endforeach; ?>

我想在 div class 中回显结果,如下所示,但我不知道如何做。如果我将 div 放在 preg_match_all 之后,它会出错。

<div class="item">
     <a href="<?php echo $item->get_title(); ?>"</a>
     <p><?php echo $item->get_description(); ?></p>
</div>

不知道该怎么做,你能帮我吗?

谢谢!

您不能在 php 中放置 html 代码。使用 php 关闭标记关闭 php 代码,然后添加 html。如下操作。

<?php
$countItem = 0;
foreach ($feed->get_items() as $item): {
    $checktitle = $item->get_permalink();
    $keyword_one = '/keyword1/';
    $keyword_two = '/keyword2/';
    if (preg_match_all($keyword_one, $checktitle, $matches) && preg_match_all($keyword_two, $checktitle, $matches)) { 
    // Closing php tag..
    ?>
        <div class="item">
             <a href="<?php echo $item->get_title(); ?>"</a>
             <p><?php echo $item->get_description(); ?></p>
        </div>
        <?php // Opening php tag after adding html..
    }
}

?>

您只需要使用 array_filterpreg_match 而不是 preg_match_all

$items = array_filter($feed->get_items(), function ($item) {
    return preg_match('/keyword1|keyword2/', $item->get_permalink());
});

foreach ($items as $item) {
    echo '
<div class="item">
     <a href="' . $item->get_title() . '"</a>
     <p>' . $item->get_description() . '</p>
</div>';
}

另外,前后端代码混合使用时要多加注意。 foreach 循环后有一个额外的 :foreach ($feed->get_items() as $item): {