removing new lines except in

后端 未结 3 616
温柔的废话
温柔的废话 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:12

    Split the content up. This is easily done with...

    $blocks = preg_split('/<(|\/)pre>/', $html);
    

    Just be careful, because the $blocks elements won't contain the pre opening and closing tags. I feel that assume the HTML is valid is acceptable, and therefore you can expect the pre-blocks to be every other element in the array (1, 3, 5, ...). Easily tested with $i % 2 == 1.

    Example "complete" script (modify as you need to)...

    
      
        test
      
      
        

    Title

    This is an article about...

          line one
          line two
          line three
        
    random
    EOF; //break it all apart... $blocks = preg_split('/<(|\/)pre>/', $html); //and put it all back together again $html = ""; //reuse as our buffer foreach($blocks as $i => $block) { if($i % 2 == 1) $html .= "\n
    $block
    \n"; //break out
    ...
    with \n's else $html .= str_replace(array("\n", "\r"), "", $block, $c); } echo $html; ?>

提交回复
热议问题