Managing Text Indentation
Learn how to manage text indentation on strings.
We'll cover the following...
Working with both spaces and tabs is not uncommon when accepting text input from users. For internal processing, it’s easier to work exclusively with spaces instead of tabs.
Implementation of the convertTabs
macro method
The helper method in the code snippet below can be used to convert tab characters into spaces using a predefined tab size:
Press + to interact
<?phpuse Illuminate\Support\Str;use Illuminate\Support\Stringable;Str::macro('convertTabs', function ($value, $tabSize = 4) {return str($value)->replace("\t", str(' ')->repeat($tabSize))->toString();});Stringable::macro('convertTabs', function ($tabSize = 4) {return new static (Str::convertTabs($this->value, $tabSize));});
We can now use our helper method to convert tab characters to spaces like so:
Press + to interact
<?php// Returns " Hello"str(' Hello')->convertTabs(4);
If you’re not used to replacing escape sequences within strings, you might wonder if this would accidentally replace a literal backslash followed by the character t
. We can do a quick experiment to prove to ourselves that this is not the case. Single-quoted strings do not support escape sequences. We can ...