Page 1 of 1

problem with < in a variable

Posted: Tue Dec 28, 2010 1:01 pm
by casall
Hi
I am having some problems with variables, hope that someone can help me out with this.

example code:
$a = "test";
$b = "<test>";
echo "$a"; -- prints: test
echo "$b"; -- prints: <nothing>

So as soon as I add "<" to the variable the variable is blank for some odd reason.

I have tried to escape it with \ but that doesn't make any difference, the $b will then only print \ and nothing else.

Running: PHP Version 5.2.6-2ubuntu4.6

Any suggestions?

Re: problem with < in a variable

Posted: Tue Dec 28, 2010 1:38 pm
by casall
found a workaround...

$a = "< test>";

If there is a space between the < and the following text it will print...

Re: problem with < in a variable

Posted: Tue Dec 28, 2010 2:41 pm
by McInfo
View the HTML source in your browser.

The browser interprets a string like "<test>" as XML. Just like you don't see the PHP source code after running a PHP script, you don't see the markup language after it is rendered in your browser window.

The way to deal with that behavior is to encode certain characters so that, when the browser decodes them, they appear as they did before the encoding. If you encode the string "<test>" as "<test>", the browser will render it as "<test>". PHP has built-in functions for this purpose: htmlspecialchars(), htmlentities().

If you don't want to bother with encoding, change the Content-Type header to plain text (for good browsers that don't force download of text files).

Code: Select all

header('Content-Type: text/plain');