【问题标题】:Filtering Date In PHP DOM在 PHP DOM 中过滤日期
【发布时间】:2012-11-01 22:01:18
【问题描述】:

我想用 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 中不起作用

【问题讨论】:

  • 我真的对你对 DOM 的引用感到困惑......你似乎在使用纯字符串。 $result 长什么样子?
  • @ÁlvaroG.Vicario 它将从页面中获取完整内容..
  • 这是一个展示它如何工作的例子。codepad.org/lAuHW565

标签: php parsing dom simple-html-dom


【解决方案1】:

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

<?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;
?>

【讨论】:

  • @MaxMuller 你是对的——我的错误——我读它为file_get_contents,即使它是file_get_html。我更改了代码以反映您的问题。
  • 什么是 OP,你能检查一下我的新线程吗 :) stackoverflow.com/questions/13380517/preg-replace-not-working 谢谢
  • @MaxMuller OP 是“原始帖子”。为什么这对你不起作用? $html 包含什么?您可以发布一个实际代码(带有真实来源,而不仅仅是示例域)吗?
  • 好的,感谢您的帮助:),假设可以用此页面中的空格替换所有这些日期prijom.com/posts/best-plugins-collection-for-drupal-7.php,我正在尝试用空格替换所有日期,同时从中获取内容page..此代码不适用于此页面:(你能帮忙吗?
  • @MaxMuller 这是因为,如果您实际查看页面的来源,您会发现日期是Apr 14 2008Sep 29 2011 等,这意味着它们(出于某种原因)在日期和年份之间放置了两个空格。我使用\s+ 编辑了正则表达式以支持多个空格(或制表符等),这意味着(空格/制表符/换行符)重复1 次或更多次(这就是+ 的含义。
猜你喜欢
  • 2015-01-20
  • 2015-02-26
  • 1970-01-01
  • 2016-03-17
  • 2017-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多