2

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.

2
  • 1
    str_replace(' ', "\t", $string) doesn't work? Commented Oct 19, 2013 at 1:56
  • It is funny to watch everyone pounce on the regex questions... :^) So many ways to solve them. Commented Oct 19, 2013 at 2:40

3 Answers 3

5

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

preg_replace('/\s+(.)\s+/', "\t$1\t", $text);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the syntax adjustment - PHP isn't my first language by a long shot :).
If there is any chance of extra spaces (e.g., different number of leading digits), I think it was "safer" before the edit, with the original \w rather than .
Yeah...I actually didn't notice the . until I posted the comment. I'd have left it with \w, but if the format is really this consistent, either's fine.
. matches any single character
3

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 

1 Comment

This is basically str_replace(' ', "\t", $text);
1
echo(preg_replace('/ /','\t','str str')."\n");//use【''】,result is:【str\tstr】,not work.
echo(preg_replace('/ /',"\t",'str str')."\n");//use【""】,result is:【str  str】,it work.

2 Comments

Can you please add an explanation!?
@WernerHenze I do agree, the answer should include any explanation on what exactly the code does and how it solves the problem. Anyhow I do believe, you can formulate this somewhat nicer. For some people this might be offending, even if just slightly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.