iOS Dev: Decoding PHP URL Encoded Strings with NSString
June 14, 2010If you do any PHP development, you should be familiar with the urlencode() function:
1 2 3 4 5 6 7 8 9 10 | <?php $string = "This string will totally screw things up if it isn't urlencoded!"; $encoded_string = urlencode($string); echo $encoded_string; // Result: // This+string+will+totally+screw+things+up+if+it+isn%27t+urlencoded%21 ?> |
Notice that the resulting string contains percent escapes in place of the apostrophe (‘%27′) and exclamation point (‘%21′), but the spaces have been replaced with ‘+’ symbols. This is what urlencode() does, and it works just fine if the encoded string will be decoded by the urldecode() function in PHP.
Things get a little more complicated if you use urlencode() to encode a query response for an iOS app. The standard, easy way to remove percent escapes is the NSString stringByReplacingPercentEscapesUsingEncoding: method. When used on the encoded string shown above, we get this:




