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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭