John
John

Reputation: 13763

Comma lost, converted to ampersand when encoding address

I have an address along the lines of the following:

123 Main Street, Boston Massachusetts, 02137

I need an address to remain intact through a URL so I tried the following:

echo urlencode($address);
echo rawurlencode($address);

The problem is that the commas keep being converted in to ampersands! 🙄︎

How do I prevent (the client? PHP? I'm not sure here) it from converting commas in to ampersands?

The HTTP query is address and the following is what happens:

print_r($_GET);

Yields:

Array (

[address] => 123 Main Street

[Boston_Massachusetts] =>

[02137] =>

)

Upvotes: 0

Views: 274

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42384

If they're getting converted to ampersands, something is going horribly wrong, as both urlencode and rawurlencode convert commas to %2C.

Encoding the string 123 Main Street, Boston Massachusetts, 02137 with rawurlencode
should give you 123%20Main%20Street%2C%20Boston%20Massachusetts%2C%2002137.

From here it's simply a matter of using rawurldecode when reading back from the URL to convert the encoded string back to your original string:

$address = "123 Main Street, Boston Massachusetts, 02137";
echo $address; // 123 Main Street, Boston Massachusetts, 02137

$encoded = rawurlencode($address);
echo $encoded; // 123%20Main%20Street%2C%20Boston%20Massachusetts%2C%2002137

$decoded = rawurldecode($encoded);
echo $decoded; // 123 Main Street, Boston Massachusetts, 02137

This can be seen working here.

Upvotes: 2

Related Questions