Remove white spaces between tags in HTML

14,990

You need use a regular expresion.

Maybe you can use this:

$html = preg_replace('/\>\s+\</m', '><', $html);

Test here https://repl.it/

Share:
14,990
Gijo Varghese
Author by

Gijo Varghese

Updated on June 04, 2022

Comments

  • Gijo Varghese
    Gijo Varghese about 2 years

    I am using the following code to remove white spaces in html. I only want to remove white spaces in betweens tags. But below code replaces all white spaces

    I.E remove all white spaces in between ">" and "<"

    //read the entire string
    $str=file_get_contents('sample.txt');
    
    //replace all white spaces
    $str=str_replace("\n", "",$str);
    $str=str_replace("\t", "",$str);
    $str=str_replace(" ", "",$str);
    
    //write the entire string
    file_put_contents('sample.txt', $str);
    
  • user38561
    user38561 over 4 years
    Another simplified version could be $html = preg_replace( '/>(\s)+</m', '><', $html );