Detect and Change Indentation With PHP

Packages

March 18th, 2022

Detect and Change Indentation With PHP

The indentation package by Colin O'Dell is a PHP library to detect and manipulate indentation of strings and files:

This package is brand-new and I am not sure what the author's plans are long-term. I thought it was interesting enough to share if you need a package to detect (or change) the indentation type of a string or file:

use ColinODell\Indentation\Indentation;
 
$indentation = Indentation::detect(file_get_contents('composer.json'));
 
$indentation->getAmount() === 4; // true
$indentation->getType() === Indentation::TYPE_SPACE; // true
(string)$indentation === ' '; // true

You can also change indentation using this package for file:

use ColinODell\Indentation\Indentation;
 
$composerJson = file_get_contents('composer.json');
$composerJson = Indentation::change($composerJson, new Indentation(1, Indentation::TYPE_TAB));
file_put_contents('composer.json', $composerJson);

You can check out this package on GitHub at colinodell/indentation to learn more and experiment with it.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.