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".

 

 

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

What he said. And to correct your code:

 

<?php
$alink = str_replace(" ", "+", str_replace("&", "&", $a));
?>

 

And when you 'print it as is', remember that the literal ampersand (&) is invalid HTML; use the html entity & (htmlentities() will give you that).

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.