Reputation: 6877
PHP: How to escape the URL params and path without encoding the Scheme and Host in URL:
Please notice* this url is just an example params might be named different than q and some urls might have path others might not, like the example below.
I get the url as follows:
http%3A%2F%2Fgoogle.com%2F?q=My%20Search%20Keyword
Then I should converted to the following:
http://google.com/?q=My%20Search%20Keyword
not:
http://google.com/?q=My Search Keyword
is there an easy way for doing this, other than
UPDATE
In more complicated case I get the URL like this:
http://www.someUrl.com/?redirect=http%3A%2F%2Fgoogle.com%2F%3Fq%3DMy%20Search%20Keyword%26hl%3Den
Where I search for =http..... then I use this part to crawl it via Curl and get the http response code from this url, the problem is that I can't easily prepare the url which was sent ecnoded from the beginning without involving the complicated process I mentioned above.
is there an easier way of doing this ?
Upvotes: 1
Views: 1600
Reputation: 6877
I came up with the following solution, it might have flaws, but might help someone else as well ..
$url = rawurldecode('http%3A%2F%2Fgoogle.com%2F%3Fq%3DMy%20Search%20Keyword%26hl%3Den');
echo preg_replace_callback('#[^/\.\:&=\?]{1}#',
function($str) { return rawurlencode($str[0]);},
$url
);
Upvotes: 0
Reputation: 15696
Try this:
<?php
$rawUrl = 'http%3A%2F%2Fgoogle.com%2F?q=My%20Search%20Keyword';
$arrDec = parse_url(urldecode($rawUrl));
$queryEnc = parse_url($rawUrl, PHP_URL_QUERY);
$newUrl = $arrDec['scheme'] . '://' . $arrDec['host'] . '?' . $queryEnc;
print_r($newUrl);
?>
Here's a phpFiddle: http://phpfiddle.org/main/code/wmi-xet
Upvotes: 1
Reputation: 64707
Can't you just explode on the ?
, then rawurldecode
the first part, then implode?
$url = "http%3A%2F%2Fgoogle.com%2F?q=My%20Search%20Keyword";
$parts = explode("?", $url);
$parts[0] = rawurldecode($parts[0]);
$url = implode("?", $parts);
Upvotes: 1