Question

I am print an string as below

Code:

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

Output:

&words=Help|Good

Notice that the last & is not printed.

But when I add a space character 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?

Was it helpful?

Solution

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.

OTHER TIPS

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']."&");

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 &amp;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top