str replace - 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




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



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

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

People are also looking for solutions to the problem: jquery - Dynamically add equal select form fields with data taken from php


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.