Search code examples
javascriptphpregexpreg-replace

Change indentation from spaces to tabs by using Regular Expressions


I have the following PHP code which changes the indentation of $html from spaces to tabs (4 spaces are replaced by 1 tab).

<?php

function indent_with_tabs($html)
{
    $indented = preg_replace('/    /', "\t", $html);
    return $indented;
}

$html = <<<EOF
<html>
    <head>
    </head>
    <body>
        <textarea rows="10" cols="40">    Hello World</textarea>
    </body>
</html>
EOF;

$indented = indent_with_tabs($html);

$expected = <<<EOF
<html>
    <head>
    </head>
    <body>
        <textarea rows="10" cols="40">    Hello World</textarea>
    </body>
</html>
EOF;

$cmp = $indented === $expected;

var_dump($cmp);

Please, notice the tabs on the expected text (StackOverflow replace them with spaces XD)...

enter image description here

My problem is: it also replaces the 4 spaces in front of the text: Hello World.

I just need to get replaced the indentation spaces without replacing inner spaces.

Could you please provide the correct code for function: indent_with_tabs(...)?

Thanks!


Solution

  • You can use

    function indent_with_tabs($html)
    {
        return preg_replace('/(?:\G|^)\h{4}/m', "\t", $html);
    }
    

    The regex matches

    • (?:\G|^) - either start of a string or end of the preceding successful match or start of a line (^ matches any line start position due to the m flag)
    • \h{4} - any four horizontal whitespaces.