Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace tabs with spaces within variables in PHP?

Tags:

$data contains tabs, leading spaces and multiple spaces. I wish to replace all tabs with a space. Multiple spaces with one single space, and remove leading spaces.

In fact somthing that would turn this input data:

[    asdf asdf     asdf           asdf   ] 

Into output data:

[asdf asdf asdf asdf]

How do I do this?

like image 859
Arthur Avatar asked Jul 25 '09 08:07

Arthur


People also ask

How do I replace a tab in a string?

In python string literals, the '\t' pair represents the tab character. So you would use mystring. replace('\t', 'any other string that you want to replace the tab with') .

How do you replace tabs with spaces in Java?

You can simply use this regular expression to replace any type of escapes( including tabs, newlines, spaces etc.) within a String with the desired one: lineOfText. replaceAll("\\s", " ");


1 Answers

Trim, replace tabs and extra spaces with single spaces:

$data = preg_replace('/[ ]{2,}|[\t]/', ' ', trim($data));
like image 192
ahc Avatar answered Sep 17 '22 15:09

ahc