SimplePie RSS解析-从get_title中随机取出单词


SimplePie RSS Parsing - Take out words randomly from get_title?

我目前正在使用SimplePie来解析RSS新闻源。我使用数组成功地合并了提要,但我需要做的是从标题中随机返回单个单词,而不仅仅是整个标题。这可以在PHP中完成吗?我在玩explode();但是运气不好。

在解析数据之后,我是否需要引入某种Javascript?我知道这有点模糊,我只是想了解什么是可能的(我愿意使用SimplePie的替代品,这正是我迄今为止使用的)。

这是我现在的代码,它只是返回整个标题:

<?php
//link simplepie
require_once ('simplepie/autoloader.php');
//new simplepie class
$feed = new SimplePie();
$feed->enable_cache(true);
$feed->set_cache_duration(60);
//set up feeds
$feed->set_feed_url(array('http://mf.feeds.reuters.com/reuters/UKTopNews' , 'http://www.theguardian.com/world/rss'
));
//run simplepie
$feed->init();
//handle content type
$feed->handle_content_type();
?>
<!DOCTYPE html>
<head>
<title>News</title>
<link rel="stylesheet" type="text/css" href='style.css'>
</head>
<body>
<div class = "headlines">
<?php foreach ($feed->get_items(0, 10) as $item): ?> 
<?php $item->get_title(); ?>
<h4><?php echo $item->get_title(); ?></h4>
<?php endforeach; ?>
</div>
</body>
</html>

谢谢!

我需要做的是从标题中随机返回单个单词

我希望我答对了你的问题,"从标题中随机返回一个单词",对吧?您的问题与SimplePie无关。每当你遇到问题时,尽量把它减少到最小的问题:这里只是一个"如何处理字符串"的问题。

对于您的用例:

$title = $item->get_title();
echo array_rand(array_flip(explode(' ', $title)), 1);

独立示例:

$string = 'This is an example headline and it contains a lot of words.';
echo array_rand(array_flip(explode(' ', $string)), 1);

这是如何工作的:

首先,标题字符串在空格字符处进行分解。你会得到一个数组。它是key=>value,其中value是字符串中的一个单词。现在,我们翻转值和键-将值作为键,然后使用array_rand()随机选择1个元素。

这可能需要一些额外的调整来删除逗号和句号,并使用特殊字符。但它应该让你开始。