benphp Posted November 14, 2007 Share Posted November 14, 2007 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 https://forums.phpfreaks.com/topic/77353-solved-i-have-an-ampersand-riddle-how-to-pass-and-use-the-in-a-url/ Share on other sites More sharing options...
kenrbnsn Posted November 14, 2007 Share Posted November 14, 2007 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 https://forums.phpfreaks.com/topic/77353-solved-i-have-an-ampersand-riddle-how-to-pass-and-use-the-in-a-url/#findComment-391623 Share on other sites More sharing options...
thebadbad Posted November 14, 2007 Share Posted November 14, 2007 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). Link to comment https://forums.phpfreaks.com/topic/77353-solved-i-have-an-ampersand-riddle-how-to-pass-and-use-the-in-a-url/#findComment-391631 Share on other sites More sharing options...
benphp Posted November 14, 2007 Author Share Posted November 14, 2007 Shweet. Thanks! That was easy. Link to comment https://forums.phpfreaks.com/topic/77353-solved-i-have-an-ampersand-riddle-how-to-pass-and-use-the-in-a-url/#findComment-391634 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.