【问题标题】:Remove white spaces between tags in HTML删除 HTML 中标签之间的空格
【发布时间】:2016-07-05 21:53:55
【问题描述】:

我正在使用以下代码来删除 html 中的空格。我只想删除标签之间的空格。但是下面的代码替换了所有的空格

即删除“>”和“

//read the entire string
$str=file_get_contents('sample.txt');

//replace all white spaces
$str=str_replace("\n", "",$str);
$str=str_replace("\t", "",$str);
$str=str_replace(" ", "",$str);

//write the entire string
file_put_contents('sample.txt', $str);

【问题讨论】:

  • 您可以使用DomDocumentpreserveWhiteSpace = false 另外还有一个问题here on SO
  • 你也可以使用 tidy
  • 既然你没有说明你的目的——为什么你想删除空格,在什么阶段——很难推荐一些具体的东西......尽管regex is not a good approach .正如丹尼尔所说,我使用了 tidy/jTiey。
  • 如果您真的想使用您的代码,您可以尝试在匹配项中包含右尖括号和左尖括号:str_replace(">\n<","><",$str)

标签: php html regex domdocument


【解决方案1】:

你需要使用正则表达式。

也许你可以用这个:

$html = preg_replace('/\>\s+\</m', '><', $html);

在这里测试https://repl.it/

【讨论】:

  • 另一个简化版可以是$html = preg_replace( '/&gt;(\s)+&lt;/m', '&gt;&lt;', $html );
猜你喜欢
  • 2012-01-17
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
相关资源
最近更新 更多