duanjitong7226 2014-05-08 18:52
浏览 37
已采纳

是否可以在preg_replace / str_replace之后格式化源代码?

I am removing several code lines from an xml file with preg_replace and str_replace

preg_replace('/(<!DOCTYPE(.*?)<fields )/s', '<fields ', $readSettings);

after the replace is done I am left with an empty spaces where the lines were. http://prntscr.com/3hegmb line 4 and 5 Is there any way to reformat the file once I am done or to remove the line and its space completely?

  • 写回答

1条回答 默认 最新

  • doumen1883 2014-05-10 13:49
    关注

    Not 100% sure what you are asking. Can you post an example of the HTML you get after the RegEx?

    This will remove excess white space.

    preg_replace( '~\s{2,}~', '', $str );
    

    You could also look at PHP DOM (PHP Manual). Load the HTML into that and then set preserveWhiteSpace and formatOutput to false.

    Addition:

    preg_replace( '~\s+
    +\s+
    +~', "
    ", $str );
    

    Will do it I think. But as mentioned you can do this with PHP DOM, and it will be more flexible.

    $doc = new DOMDocument();
    $doc->loadHTML( $html );
    $doc->preserveWhiteSpace = true; // Or false?
    $doc->formatOutput = true;
    echo $doc->saveHTML();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效