【问题标题】:how to remove multiple whitespaces and newline character from HTML entity如何从 HTML 实体中删除多个空格和换行符
【发布时间】:2015-10-08 20:31:01
【问题描述】:

我正在尝试使用 codeigniter 和 simplehtmldom 实现爬虫。

$page = "URL to be Crawled";
$html = file_get_html($page);
$ad_description = $html->find('#ad_description',-1);
$description = $ad_description->innertext;

$description 包含多个连续的空格和换行符,我需要将其转换为单个外观。

我试过了

str_replace("\n\r",' ',$description),
reduce_multiples($ad_description->innertext,"\r")
preg_replace("/[\r\n]+/", "\n", $description)
ascii_to_entities($description,ENT_HTML5, "ISO-8859-1")

和许多其他可能的选择,但没有成功。任何帮助将不胜感激。

【问题讨论】:

  • 你可以从他的stackoverflow.com/questions/6360566/…得到想法
  • 即使 preg_replace 也不起作用。
  • 我什至尝试过以上选项的组合。他们都没有工作。 find() 函数返回不受普通字符串操作约束的 HTML 实体。如果有人可以建议如何将此实体转换为字符串。可能上述选项会起作用。
  • 你能不能 echo 或 var_dump $description
  • 是的,我可以回显描述它回显多个换行符和多个空格

标签: string codeigniter newline simple-html-dom removing-whitespace


【解决方案1】:

我认为 pref_replace 确实有效

$description = "This
is      a
test   string
";

echo $description = preg_replace('/\s+/', ' ', $description); // This is a test string 

【讨论】:

  • 上述上下文绝对有效。但是当我使用 $html->find() 时它不起作用
  • preg_replace之前和之后显示var_dump($description);
猜你喜欢
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多