Jump to content

[SOLVED] I have an Ampersand riddle - how to pass and use the & in a URL?


benphp

Recommended Posts

I've been working on this for a while now and still can't seem to get it to work.

 

I want to pass a phrase in the URL that uses an ampersand:

 

"Black & White"

 

And I want to be able to 1) print it as is, and 2) insert it into a link. I think the problem lies in the spaces around the ampersand. I've tried various methods of replacing it with & and &038; and replacing the spaces with %20 or + but it still causes trouble.

 

Note - this looks simple but it isn't.

 

Here's the test code:

 

<?php
$a = "";
if (isset($_GET['a'])) {
$a = $_GET['a'];
}

print "a=$a";

$alink = str_replace("&", '&', $a);
$alink = str_replace(" ", '+', $a);

print "<p><a href=\"test.php?a=$alink\">Test</a><p>";

print "
<html>
<head></head>
<body>
<form action=\"test.php\" method=\"GET\" name=\"myform\">
<input type=\"text\" name=\"a\" value=\"$a\"><br />
<input type=\"Submit\" name=\"btnGo\">
</form>
</html>
";

?>

 

To see what I mean:

1. Enter Black & White into the field.

2. Click Submit.

3. Click the link that was created.

 

You will see that only "Black" was retained in the link, even though the link variable looks like "test.php?a=black+&+white".

 

 

Link to comment
Share on other sites

Use the function rawurlencode()

 

<?php
$a = "";
if (isset($_GET['a'])) {
$a = $_GET['a'];
}

print "a=$a";


echo  '<p><a href="test.php?a=' . rawurlencode($a) . '">Test</a><p>';

print "
<html>
<head></head>
<body>
<form action='test.php' method='GET' name='myform'>
<input type='text' name='a' value='" . rawurlencode($a) . "'><br />
<input type='Submit' name='btnGo'>
</form>
</html>
";

?>

 

Ken

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.