使用正则表达式过滤RSS链接

时间:2016-02-25 10:21:06

标签: php regex if-statement rss

我有点像菜鸟,但是我已经开始在本地主机上用PHP建立一个网站了。我遇到的问题是,我无法弄清楚如何过滤在其链接中包含正则表达式的RSS内容。

使用PHP显示RSS源的代码:

<?php
 ///// RSS FEED CODE
 function getFeed1($feed_url) { 
     $content = file_get_contents($feed_url);
     $x = new SimpleXmlElement($content);
     echo "<ul>";   
         foreach($x->channel->item as $entry) {
         echo "<li><a href='$entry->link'     title='$entry->title'>" . $entry->title . "</a></li>";
         }
    echo "</ul>";
}   
getFeed1("http://www.drf.com/feeds/all-articles-of-track/SA");
?>

结果在浏览器中显示为指向页面的链接

 Espinoza wins George Woolf Memorial Jockey Award
 Dortmund will get month to clear up foot problem
 Abrams hopes McHeat stays hot for Sensational Star
 Santa Anita attendance up, handle down
 Hot Market returns from long absence on hillside turf course
 Moon Over Paris, Divina Comedia key to pick six
 Millionaire Alert Bay looks to pad bankroll in Sensational Star
 Santa Anita to replace turf course this summer
 Free: Santa Anita horses to watch for week of Feb. 22
 Iron Rob vanned off after winning Baffle Stakes

我试图找出如何使用if语句来过滤掉以“http://www.drf.com/news/preview/”开头的链接(href)。

所以结果如下:

 Espinoza wins George Woolf Memorial Jockey Award
 Santa Anita attendance up, handle down
 Millionaire Alert Bay looks to pad bankroll in Sensational Star
 Santa Anita to replace turf course this summer
 Iron Rob vanned off after winning Baffle Stakes

我在最近两天尝试了不同的变体:

 if (strpos($x, 'http://www.drf.com/news/preview/') !== false) 

 if (preg_match('http://www.drf.com/news/preview/', $x))        

然而,我无法正确使用语法,或者我在某个地方搞砸了。

我发现帖子建议使用第三方过滤器或死yahoo管道,但我感觉我所寻求的可以用if语句完成。我还没有找到任何可以使用正则表达式解析rss href的东西。

对于了解php的人,我错过了什么?我花了最近两天谷歌搜索和尝试在互联网上提到的不同的东西,但无济于事。我知道追逐总是比捕获更好,但我失去了猎物的踪迹。请指点我和其他发现这篇文章的人找到帮助。

谢谢

1 个答案:

答案 0 :(得分:0)

这是您正在寻找的正则表达式:

/^(http\:\/\/www\.drf\.com\/news\/preview\/)/i

您也应该通过一些小修改来接受HTTPS:

/^(https?\:\/\/www\.drf\.com\/news\/preview\/)/i

不要回到www子域名!

/^(https?\:\/\/(www\.)?drf\.com\/news\/preview\/)/i
相关问题