PHP: Change Tabs to Spaces and Vice Versa in String | Change Tab Sizes / Lengths in Strings

Everyone who ever dealt with formatting code in PHP string manipulations may want to switch between different tab sizes or simply change spaces to tabs or tabs to spaces in the formatted code string.

The function we’ll need for these is str_replace(), the string search and replace php function. For example:

Switch between tabs and spaces

By spaces, I mean spaces used to start a new line of code that indents that line rather than all the spaces including those used simply between words. Therefore, you generally want to change tabs to spaces in double:

$spaced = '(spaces) some code';
$tabbed = str_replace('  ', "\t", $spaced); // 2 spaces is the 1st parameter

To change tabs back to spaces (preferably in double spaces as well, such as 4 spaces), just reverse the process:

$tabbed = '(tabs) some code';
$spaced = str_replace("\t", '    ', $tabbed); // 4 spaces is the 2nd parameter

“\t” is the byte representation of a tab.

Change tab sizes / lengths

Essentially the same, just use the function str_replace() to change the number of spaces used in place of a tab.

Scroll to Top