【问题标题】:Unable to remove space in the plaintext with the use of simplehtmldom无法使用 simplehtmldom 删除明文中的空格
【发布时间】:2015-02-04 07:59:24
【问题描述】:

我正在使用 simplehtmldom 来获取一些网站数据

$data = array();
$html = file_get_html('http://www.example.com/'.$value, false, $context);
foreach($details as $value){

   $dataele = array();

    foreach($html->find('*[class=style11]') as $element){

      $houseinfo = trim($element->plaintext, " \t\n\r\0\x0B\xC2\xA0");
      echo $houseinfo;
      echo '<br>';
      array_push($dataele, $houseinfo);

    }   
}

但是当我将这些数据插入数据库时​​,我发现有一些&amp;nbsp;。 我尝试了不同的方法,但它不能真正删除&amp;nbsp; html 标记。我尝试过的方法:

$houseinfo = trim($element->plaintext, " \t\n\r\0\x0B\xC2\xA0");
$dataele[1] = html_entity_decode($dataele[1]);
$dataele[1] = str_replace("&nbsp;", "_", $dataele[1]);
$houseinfo = filter_var($houseinfo, FILTER_SANITIZE_STRING);
$dataele[1] = preg_replace("/&#?[a-z0-9]+;/i", "", $dataele[1]);

【问题讨论】:

  • Note: You might wonder why trim(html_entity_decode('&amp;nbsp;')); doesn't reduce the string to an empty string, that's because the '&amp;nbsp;' entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 encoding.
  • @Class 你能告诉我如何让它工作吗?
  • 如果您使用诸如urlencode 之类的方法回显HTML,您将能够看到隐藏了哪些字符(如果有的话),以及为什么您的东西没有被替换..
  • @h2ooooooo 非常感谢,我已经找到问题所在了。我刚刚发现那是 &amp;nbsp ,而不是 &amp;nbsp; ...

标签: php preg-replace trim simple-html-dom


【解决方案1】:

希望这会有所帮助。

    $string = str_replace(' ', '-', htmlspecialchars_decode($element->plaintext)); 
            $string = preg_replace('/[^A-Za-z0-9-_!@#:$%^&*\/()+={}<>?;, \-]/', '', $string);
            $string = preg_replace('/-+/', ' ', $string);
    echo $string;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 2016-06-03
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多