0

使用PHP Simple HTML DOM Parser获取 span 类的前三个单词的方法是什么。
假设获取页面的源代码为:

Some Text <span class="sos">Good Better Best <i> Some text</i> here</span>Again 这里有一些文字

使用 php simple html dom parser 我们可以像这样获取 span 类的所有内容:

$data = $html->find('span class="sos"');

所以在这里,$data将声明该跨度类的全部内容。
我想做的是只在新变量中获取跨度类的前三个单词,所以在这种情况下应该是:

$new_data = 'Good Better Best';

怎么做?
PHP 简单 HTML DOM 解析器手册

4

3 回答 3

1

您可以尝试为此使用爆炸。

$data = $html->find('span class="sos"');
$breakdata = explode(" ",$data);
$firstThreeWords = array_slice($breakdata, 0, 3);

$final = implode(" ",$firstThreeWords); //Good Better Best

如果要排除前三个单词,

$data = $html->find('span class="sos"');
$breakdata = explode(" ",$data);
$removeFirstThreeWords = array_slice($breakdata, 2);

$final = implode(" ",$removeFirstThreeWords ); //Some text here
于 2012-11-02T10:51:16.657 回答
1

类似于上面的答案,但用于strip_tags预先从字符串中删除 HTML。

$output = implode(' ', array_slice(explode(' ', strip_tags($data)), 0, 3));
于 2012-11-02T10:56:11.313 回答
1

正如您评论@billyonecan post ,听起来您的解决方案是:

$result = str_get_html($result);
foreach($html->find('.sos') as $xdat)
{
$x_des = implode(' ', array_slice(explode(' ', strip_tags($xdat)), 0, 3));
$result = str_replace($x_des, ' ', $result);
$result = str_get_html($result);
}

根据您的需要更改所有变量。

于 2012-11-02T14:16:55.107 回答