Home > Mobile >  Remove excess whitespace/indentation from strings
Remove excess whitespace/indentation from strings

Time:05-08

I have a string like:

     section
        subsection
            text

I'd like to remove the white space from the first line, and the same amount of white space from the following lines. It's to automatically de-indent some text used as a description pulled from something else, but retaining the relative indentation, like this :

section
   subsection
       text

Is there a clean way to do this? I thought originally of counting the space characters at the start, but they might be indent with tabs (though i'd assume all lines are indented the same way).

CodePudding user response:

Grab initial white-space:

preg_match('/^(?<initial>\s*)/', $input, $match);
['initial' => $initialWhiteSpace] = $match;
$whiteSpaceLength = strlen($initialWhiteSpace);

Convert string to array of lines:

$lines = explode(PHP_EOL, $input);

Remove the white-space:

$output = array_map(
    static fn (string $str): string => preg_replace(sprintf("/^[ \t]{%d}/", $whiteSpaceLength), '', $str),
    $lines,
);

Recreate the string:

$output = implode(PHP_EOL, $output);

Et voila:

echo $output;

Proof of concept: https://3v4l.org/GoFbG

CodePudding user response:

I rewrote emix's PHP7.4 code to work in 5.6 but the basics are the same :

function strip_indentation ($input) {
  preg_match('/^(?<initial>\s*)/', $input, $match);
  $whiteSpaceLength = strlen($match['initial']);
  $lines = [];
  foreach(explode(PHP_EOL, $input) as $key => $line)
  {
     $lines[$key] = preg_replace(sprintf("/^[ \t]{%d}/", $whiteSpaceLength), '', $line);
  }

  $output = implode(PHP_EOL, $lines);
  return $output;
}
  • Related