faq
faq

Reputation: 3076

Strip unwanted spaces then url_encode a string

I want to strip all spaces that are not between two words and then url-encode a string.

$string = "              bah bah    bah  ";
$string = str_replace("/w /w", "+", $string);
// I want string to look like this:
$string = "bah+bah+bah"; 

The idea is that I want to get rid of all unnecessary spaces (not only at the beginning and end).

Upvotes: 1

Views: 814

Answers (3)

Glass Robot
Glass Robot

Reputation: 2448

trim will remove the whitespace at the beginning and end:

$string = trim($string);
echo str_replace(" ", "+", $string);

Upvotes: 4

genesis
genesis

Reputation: 50966

$string = str_replace("/w /w", "+", trim($string));

trim() deletes all unnecessary spaces

Upvotes: 1

Michael Berkowski
Michael Berkowski

Reputation: 270609

Can you not just trim whitespace and use urlencode() to convert the interior spaces to +? If you have other characters which cannot tolerate being url encoded, this will not work. But we don't know your full requirements.

urlencode(trim($string));


$string = "              bah bah";
echo urlencode(trim($string));

// bah+bah

Upvotes: 3

Related Questions