tags:

views:

80

answers:

3

I am print an string as below

Code:

echo "&words=".$rs['pw']."&";

Output:

&words=Help|Good

Notice that "&" is not printed.

But when I am giving "space" after "&" then it gets printed as below

Code:

echo "&words=".$rs['pw']."& ";

Output:

&words=Help|Good&

Now "&" is printed.

Why its happening and whats the reason for this behavior?

THANKS

+1  A: 

This code works for me

$rs['pw'] = "Help|Good";
echo "&words=".$rs['pw']."&";

Output

&words=Help|Good&

Which leads me to a question: What is the context? Where is this code output, are you running it on a webserver and viewing in a browser? Is there no other code involved that can be causing this?

If the context is something like outputting in HTML then you need to make sure that it is in the right place. In HTML ampersand is special and you should escape it. Usually that means translating into &

Peter Lindqvist
Yes, I am running it on web server and viewing it in browser and no other code included there, I just seen this so I have removed all the code and then tested it, still the same issue.
Prashant
Ok i tested it on my webserver and it still works. Have you tested the exact code that i've given or do you have _any_ other code at all in your file? Like reading from database or anything?
Peter Lindqvist
+1  A: 

If you're outputting it in a web page, then the browser will interpret & special. Select at "view source" in your browser, and you will see the raw output. If you need it to appear in a html context, you will have to pass the string through htmlspecialchars before printing it. So:

$rs['pw'] = "Help|Good";
echo htmlspecialchars("&words=".$rs['pw']."&");
troelskn
+3  A: 

If you're outputting it to a web browser you should be escaping the & by using &amp; "&" in HTML is used a lot to escape strings, and in URL's so is a special char, like <> etc.

Schkib