Reputation: 9918
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
$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.
Upvotes: 1
Views: 29728
Reputation: 2528
There is a built-in PHP function for this, which is a far better option than doing it manually.
urlencode - built in function from php
However, if you still want to do it manually:
function convert_text($text) {
$t = $text;
$specChars = array(
'!' => '%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',
',' => '%E2%80%9A', ' ' => '%20'
);
foreach ($specChars as $k => $v) {
$t = str_replace($k, $v, $t);
}
return $t;
}
place the key and value in the last so that the last iteration of loop will be for spaces
Upvotes: 8
Reputation: 12916
Wouldn't you be better off using the PHP build in functionality to do this: rawurlencode?
Upvotes: 4
Reputation: 763
You can use rawurlencode($url)
builtin function.
<?php
$url='http://fb.com';
echo rawurlencode($url);
the output:
http%3A%2F%2Ffb.com
Upvotes: 2
Reputation: 890
Do not use a loop.
Use str_replace
str_replace($entities, $replacements, $string);
Or better use this native PHP function rawurlencode
Upvotes: 4
Reputation: 522085
There's already a function for this in the standard PHP library: rawurlencode
.
Upvotes: 2