【问题标题】:Remove part of string from array value in PHP从PHP中的数组值中删除部分字符串
【发布时间】:2012-12-21 19:57:09
【问题描述】:

我有以下代码 sn-p,它基本上解析我的博客站点并将一些信息存储为变量:

global $articles;

$items = $html->find('div[class=blogpost]'); 

foreach($items as $post) {
    $articles[] = array($post->children(0)->innertext,
                        $post->children(1)->first_child()->outertext);
}

foreach($articles as $item) {
    echo $item[0]; 
    echo $item[1];
    echo "<br>";
}

以上代码输出如下:

Title of blog post 1 <script type="text/javascript">execute_function(3,'')</script><a href="http://www.example.com/cool_news" id="963"  target="_blank" >Click here for news</a> &nbsp;<img src="/news.gif" width="12" height="12" title="validated" /><span class="title">
Title of blog post 2 <script type="text/javascript">execute_function(3,'')</script><a href="http://www.example.com/neato" id="963"  target="_blank" >Click here for neato</a> &nbsp;<img src="/news.gif" width="12" height="12" title="validated" /><span class="title">
Title of blog post 3 <script type="text/javascript">execute_function(3,'')</script><a href="http://www.example.com/lame" id="963"  target="_blank" >Click here for lame</a> &nbsp;<img src="/news.gif" width="12" height="12" title="validated" /><span class="title">

$item[0] 包含“博客文章 X 的标题”,$item[1] 包含其余部分。

我想要做的是解析 $item[1] 并仅保留其中包含的 URL 作为单独的变量。也许我没有正确地表达我的问题,但我找不到任何可以帮助我解决这个问题的东西。

谁能帮帮我?

【问题讨论】:

标签: php arrays variables html-parsing extract


【解决方案1】:

如果您要将 $item[1] 解析为用于 $html 的任何 DOM 爬虫对象,则可以使用以下 XPath

$item[1]->find('//a[0]/@href');

会返回的

href="http://www.example.com/cool_news"

然后使用 PHP 提取您想要的 url 或优化 XPath 查询。不知道 XPath 将是什么来获得价值,也许有人可以扩展那个。

编辑:当您使用 Simple DOM Parser 时,请尝试以下操作

$blogItemHtml = new simple_html_dom();
$blogItemHtml->load($item[1]);

$anchors = $blogItemHtml->find('a');
echo $anchors[0]->href; // "http://www.example.com/cool_news"

【讨论】:

猜你喜欢
  • 2013-05-17
  • 2011-05-06
  • 2011-04-20
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多