phptrimurlencode

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


Solution

  • 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