【问题标题】:How to remove all line breaks OUTSIDE of html tags如何删除html标签之外的所有换行符
【发布时间】:2014-01-16 11:16:12
【问题描述】:

我正在通过 php 脚本清理一些 html 文件,我想删除所有不在 <tag></tag> 之间的 \n 东西。

<p>some text</p>


           <- here are the bunch of \n I want to remove


<p>some other random
text with \n at fixed width
and that's great</p>

有什么想法吗? 非常感谢。

【问题讨论】:

  • 您的意思是在&lt;body&gt; 标签内但在其任何子标签外。
  • 在 html 代码中的任何 之外。 不好
  • 为此使用 DOM 解析器,并删除所有只是空白的子标签。你已经看过DOMDocument的文档了吗?
  • 您的 HTML 中没有任何 &lt;html&gt; 标记?怎么会这样?
  • 另外,请注意换行符与 HTML 渲染器的空格完全相同,除非您在 CSS 中另有声明。而不是使用nl2br(就像我猜你做的那样),使用CSS来指定换行符应该保留在你想要保留它的标签内。

标签: php html string


【解决方案1】:

这样就够了?

<?php
$html=<<<SOMECONT
<p>some text</p>





<p>some other random
text with \n at fixed width
and thats great</p>
SOMECONT;

$narr=array_filter(explode(PHP_EOL,$html),'strlen');
echo implode('',$narr);

输出:

<p>some text</p><p>some other randomtext with 
 at fixed widthand thats great</p>

编辑:替代

可能更“脏”但有效。毕竟,删除 htmltags 之间的所有 \n 有时就像从原始文件的分解字符串中删除空行一样简单。

  $split = explode(PHP_EOL,$data);
  $data= "";
  for($i = 0; $i < count($split); $i++){
    $line = $split[$i];
    else if(strlen($line) > 0) $data .= $split[$i]."\n"; // filter
  }

【讨论】:

  • 那不会也删除 html 标签之间的换行符吗?
  • 这里的 strlen 评估长度是否 > 0 以删除每个“空行”对吗?它应该工作,但不知何故它不是。但是我创建了一种肮脏的方式来做同样的事情,在 PHP_EOL 上进行爆炸,然后使用 strlen() 进行过滤。谢谢
  • @Lego,很高兴你成功了。您可以像以前一样编辑此答案,以便其他人受益!。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多