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

Trim, replace tabs and extra spaces with single spaces:

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

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".


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