Monday, February 21, 2011

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

$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

Input data:
[    asdf asdf     asdf           asdf   ]

Into output data:
[asdf asdf asdf asdf]

How do i do this?

From stackoverflow
  • $data = trim(preg_replace('/\s+/g', '', $data));
    
    Matthew Scharley : You also forgot to mention trim to get rid of leading spaces. Probably want to mention ltrim too, since he asked for leading spaces then illustrated both ends.
    RaYell : Yeah, thanks for pointing that. In the example it's shown that both leading and trailing spaces should be removed so I updated my code.
  • $data = trim($data);
    

    That gets rid of your leading (and trailing) spaces.

    $pattern = '/\s+/';
    $data = preg_replace($pattern, ' ', $data);
    

    That turns any collection of one or more spaces into just one space.

    $data = str_replace("\t", " ", $data);
    

    That gets rid of your tabs.

  • Assuming the square brackets aren't part of the string and you're just using them for illustrative purposes, then:

    $new_string = trim(preg_replace('!\s+!', ' ', $old_string));
    

    You might be able to do that with a single regex but it'll be a fairly complicated regex. The above is much more straightforward.

    Note: I'm also assuming you don't want to replace "AB\t\tCD" (\t is a tab) with "AB CD".

  • $new_data = preg_replace("/[\t\s]+/", " ", trim($data));
    
  • Trim, replace tabs and extra spaces with single spaces:

    $data = preg_replace('/[ ]{2,}|[\t]/', ' ', trim($data));
    

0 comments:

Post a Comment