Search code examples
phpfilterpreg-matchpreg-match-all

filter feed titles with preg_match_all


Help me with this please :)

I have this code which filters the feed titles. However this comes in a messy unordered list.

$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; ?>

I want to echo the results in a div class as below, but I don't know how. It gives an error if I place the div after preg_match_all.

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

Not sure how to do, can you help me with that?

Thank you!


Solution

  • You just need to use array_filter and preg_match instead of 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>';
    }
    

    Also, pay more attention when mixing between frontend and backend code. You have an extra : after the foreach loop: foreach ($feed->get_items() as $item): {