在PHP DOM中过滤日期

时间:2012-11-13 13:12:32

标签: php parsing dom simple-html-dom

我想使用SIMPLE HTML PHP DOM PARSER(simplehtmldom.sourceforge.net)用所提取内容中的空格替换所有日期。这是代码:

include("simple_html_php_dom.php");
$html = file_get_html("http://freebacklinks.prijm.com"); //example.com
$result = "$html";
$result = preg_replace("/([1-9]|[0-2][0-9]|3[0-1]) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]{4}/", " ", $result);
$result = preg_replace("/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([1-9]|[0-2][0-9]|3[0-1]) [0-9]{4}/", " ", $result);
echo $result;

因此,此处所有日期数据如:01 Jan 2004Jan 01 2004Dec 12 14都应替换为空格......但它不会用空格替换这些日期..现在该怎么做怎么办?
以下是一个示例,说明它如何运作.. http://codepad.org/lAuHW565 ,但为什么它无效PHP Simple HTML DOM Parser

1 个答案:

答案 0 :(得分:2)

你试图替换一个不可能的SimpleHTML对象(它是一个对象,而不是一个字符串)。您应该首先获取HTML,然后替换,然后使用SimpleHTML函数将其转换为str_get_html

<?php
    include("simple_html_php_dom.php");

    //Start with getting the pure HTML and replacing in that (don't use SimpleHTMLPHP for this)
    $html = file_get_contents("http://freebacklinks.prijm.com"); //example.com
    $html= preg_replace("/([1-9]|[0-2][0-9]|3[0-1])\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+[0-9]{4}/", " ", $html);
    $html = preg_replace("/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+([1-9]|[0-2][0-9]|3[0-1])\s+[0-9]{4}/", " ", $html);

    //Now create the $result variable:
    $result = str_get_html($html);
    echo $result;
?>