removing new lines except in

后端 未结 3 608
温柔的废话
温柔的废话 2021-01-14 19:24

I want to remove new lines from some html (with php) except in

 tags where whitespace is obviously important.

3条回答
  •  一向
    一向 (楼主)
    2021-01-14 20:13

    It may be 3 years later, but... The following code will remove all line breaks and whitespace at long as it is outside of pre tags. Cheers!

    function sanitize_output($buffer)
    {
        $search = array(
            '/\>[^\S ]+/s', //strip whitespaces after tags, except space
            '/[^\S ]+\',
            '<',
            '\\1'
            );
    
        $blocks = preg_split('/(<\/?pre[^>]*>)/', $buffer, null, PREG_SPLIT_DELIM_CAPTURE);
        $buffer = '';
        foreach($blocks as $i => $block)
        {
          if($i % 4 == 2)
            $buffer .= $block; //break out 
    ...
    with \n's else $buffer .= preg_replace($search, $replace, $block); } return $buffer; } ob_start("sanitize_output");

提交回复
热议问题