Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex replace space with tab character

Tags:

regex

php

I need to replace the space between the first and second column and second and third column with a \t only.

0101 A 01/13/13
0102 F 04/05/13
0209 C 04/19/13

But i am having trouble doing this, it is putting it all in one line and writing out \t instead.

preg_replace('/(?:^|\s)/', '\t', $text);

Its printing it out as so....

\t0101\tA\t01/13/13\t\t ....

How can i properly get this in the correct format?

Any help appreciated.

like image 354
paulie.jvenuez Avatar asked Sep 15 '26 06:09

paulie.jvenuez


2 Answers

If your data is in a strict format like this, why not

preg_replace('/\s+(.)\s+/', "\t$1\t", $text);
like image 139
Josh Avatar answered Sep 17 '26 21:09

Josh


Just search for a literal space and replace with \t... Unless your data vary more than that, none of the (?:) is necessary.

Are there other spaces? Are there more columns?

preg_replace('/ /',"\t", $text);

If I make a test.php file with:

<pre>
<?php 
$t="0101 A 01/13/13\n0102 F 04/05/13\n0209 C 04/19/13"; 
printf(preg_replace('/ /',"\t",$t));  
?> </pre> 

It generates this:

0101    A   01/13/13
0102    F   04/05/13
0209    C   04/19/13 
like image 26
beroe Avatar answered Sep 17 '26 21:09

beroe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!