【问题标题】:How to remove all kind of non-breaking spaces with php如何使用php删除所有类型的不间断空格
【发布时间】:2019-10-05 20:49:32
【问题描述】:

我正在将 Html 文件中的字符串保存到我的数据库中。 我无法修剪字符串并清除空格。

我创建了这个简化的函数来总结问题以及我到目前为止所做的尝试。

<?php

function get_content($html)
{
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $div = $dom->getElementById('whitespace');
    $content = $div->textContent;
    # Goal:  trim leading, trailing, and non-breaking space
    $content = str_replace('&nbsp;','',$content);
    $content = str_replace('U+00A0','',$content);
    $content = str_replace('\u00a0','',$content);
    $content = str_replace('\xa0','',$content);
    $content = str_replace(chr(160),'',$content);

    $content = trim($content);
    return $content;
}

file_put_contents(
    'trim.output',
    get_content('<div id="whitespace">&nbsp; &nbsp; &nbsp; TuffToTrim</div>'
));
?>

输出是:

      TuffToTrim

虽然我希望它是:

TuffToTrim

此时我有点绝望:) 有什么想法吗?

【问题讨论】:

  • 我认为您只替换不间断空格,但保留正常空格。将它们替换为$content = str_replace(' ','',$content);
  • 也许先转换一下: $content = htmlentities($content, null, 'utf-8'); $content = str_replace(" ", "", $content);
  • $div-&gt;textContent 对那里的&amp;nbsp; 做了一些奇怪的事情。当您将文本直接粘贴到 $content 中时,一切都很好。我知道这还没有帮助 - 但它可能会提示进一步搜索的地方。
  • @equi 谢谢!这是完美的解决方案。我了解了 htmlentities 和 htmlspecialchars。
  • @StoyanGeorgiev 不客气。我很高兴这很有帮助。我会把它作为答案发布,所以它也可以帮助其他人。

标签: php whitespace


【解决方案1】:

首先应该将其转换为 HTML 实体。那么你应该可以替换字符了。

$content = htmlentities($content, null, 'utf-8'); 
$content = str_replace("&nbsp;", "", $content);

【讨论】:

    【解决方案2】:

    代替

    $content = str_replace('&nbsp;','',$content);
    $content = str_replace('U+00A0','',$content);
    $content = str_replace('\u00a0','',$content);
    $content = str_replace('\xa0','',$content);
    $content = str_replace(chr(160),'',$content);
    $content = trim($content);
    

    你应该使用

    $content = preg_replace('/[\s]+/mu', '', $content);
    

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 2013-06-22
      • 2019-04-24
      • 2015-01-28
      • 2017-03-17
      • 2021-01-17
      • 2012-07-28
      • 2017-05-19
      • 2012-08-24
      相关资源
      最近更新 更多