I am trying to convert special characters (eg. +
, /
, &
, %
) which I will use them for a GET request. I have constructed a function for this.
function convert_text($text) {
$t = $text;
$specChars = array(
' ' => '%20', '!' => '%21', '"' => '%22',
'#' => '%23', '$' => '%24', '%' => '%25',
'&' => '%26', '\'' => '%27', '(' => '%28',
')' => '%29', '*' => '%2A', '+' => '%2B',
',' => '%2C', '-' => '%2D', '.' => '%2E',
'/' => '%2F', ':' => '%3A', ';' => '%3B',
'<' => '%3C', '=' => '%3D', '>' => '%3E',
'?' => '%3F', '@' => '%40', '[' => '%5B',
'\\' => '%5C', ']' => '%5D', '^' => '%5E',
'_' => '%5F', '`' => '%60', '{' => '%7B',
'|' => '%7C', '}' => '%7D', '~' => '%7E',
);
foreach ($specChars as $k => $v) {
$t = str_replace($k, $v, $t);
}
return $t;
}
When I use some text
as input for the function, I should get some%20text
. But, because I do this replacement in a foreach loop, it first replaces 'space' to %20
and in the second step it replaces %
character to %25
. Eventually I get some%2520text
.
Is there any other way or a built in function to make this substitution?
rawurlencode replaces all the
EDIT
$t = str_replace(array_keys($specChars), array_values($specChars), $text);
I have used str_replace without loop as SpongePablo suggested.
It gives the same result which I do not desire. On the other hand, if I use rawurlencode
, it converts some other characters which I don't want them to be converted.
Wouldn't you be better off using the PHP build in functionality to do this: rawurlencode?
Do not use a loop.
Use str_replace
Or better use this native PHP function rawurlencode
There's already a function for this in the standard PHP library:
rawurlencode
.place the key and value in the last so that the last iteration of loop will be for spaces
other than that you can use
You can use
rawurlencode($url)
builtin function.the output: