Utility.php

<?php

namespace Tlf\Lexer;

class Utility {

    /**
     * Trim trailing whitespace from each line
     */
    static public function trim_trailing_whitespace(string $str){
        $regex = '/\s+$/m';
        $clean = preg_replace($regex, '', $str);
        return $clean;
    }

    /**
     * Remove leading indents from every line, but keep relative indents
     * @return string
     */
    static public function trim_indents(string $str){
        //separate first line
        $str = str_replace("\r\n", "\n", $str);
        $lines = explode("\n", $str);
        $firstLine = array_shift($lines);
        while (count($lines)>0&&trim($lines[0]) === ''){
            array_shift($lines);
        }

        // find smallest indent
        $smallestIndent = 9999;
        foreach ($lines as $index=>$line){
            if (trim($line)=='')continue;
            preg_match('/^(\s*)/', $line, $match);
            $indent = $match[1];
            if ($smallestIndent==-1)$smallestIndent = strlen($indent);
            else if ($smallestIndent>strlen($indent))$smallestIndent = strlen($indent);
        }
        // remove indent
        foreach ($lines as $index=>$line){
            if (strlen($line) < $smallestIndent)$lines[$index] = '';
            else $lines[$index] = substr($line,$smallestIndent);
        }
        // re-insert first line
        if (strlen($firstLine=trim($firstLine))>0){
            array_unshift($lines, trim($firstLine));
        }

        //remove trailing blank lines
        $lastLine = false;
        while (count($lines)>0 &&
            trim($lastLine = array_pop($lines))===''
        ){
            // if (trim($lastLine)=='')continue;
        }
        if (is_string($lastLine)){
            $lines[] = $lastLine;
        }

        return implode("\n", $lines);
    }
}