faq
faq

Reputation: 3076

strip all unnecessary spaces in a php string

I want to strip all spaces that are not between two letters:

$string = "              bah    bah    bah bah  ";
$string = str_replace("/w /w", "+", $string);
// what goes here? to get this:
$string = "bah+bah+bah+bah"; 

The idea is that i want to get rid of all unnecessary spaces(not only at the beginning and end). This is not for a link but for a search box that on submit will be exploded so the + can even be a = or anything basically

Upvotes: 3

Views: 3709

Answers (2)

casraf
casraf

Reputation: 21694

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

Upvotes: 7

Jason McCreary
Jason McCreary

Reputation: 72981

If your ultimate goal is to explode a search string (i.e. into an array of terms) I suggest condensing all steps into one using preg_split()

$search_terms = preg_split('/\s+/', $search_string);
print_r($search_terms);

Upvotes: 3

Related Questions