0

For some reason I am unable to print this string: 'ggukjbgfjI:2<EiK6'. There is no escape for "<" that I am aware of.

<?php
$x = 'ggukjbgfjI:2<';
$y = 'EiK6';
$z = 'ggukjbgfjI:2<EiK6';
echo $x;
echo $y;
echo "<br><br>";
echo $z;
?>
2
  • It is printed, but if viewed with a browser it would be parsed as sign to open a tag. See with (rightclick show source in browser). You can escape it for HTML like echo htmlspecialchars($z);. Commented May 2, 2024 at 20:42
  • 1
    php.net/manual/en/function.htmlspecialchars.php Commented May 2, 2024 at 20:43

1 Answer 1

0

If you view page source in your browser, you will see that your code actually outputs:

ggukjbgfjI:2<EiK6<br><br>ggukjbgfjI:2<EiK6

But in the browser you only see:

ggukjbgfjI:2
ggukjbgfjI:2

So what gives? This is because < is the opening character of an <html> tag, meaning that the browser is parsing everything inside it as HTML code until it meets a > character.

The solution to this, is to encode the < as an HTML entity, ie. &lt;

So if you have the code:

$x = 'ggukjbgfjI:2&lt;';
$y = 'EiK6';
$z = 'ggukjbgfjI:2&lt;EiK6';
echo $x;
echo $y;
echo "<br><br>";
echo $z;

It will output, as you'd expect:

ggukjbgfjI:2<EiK6

ggukjbgfjI:2<EiK6

There is also a built in PHP function htmlspecialchars to encode special characters for you automatically, so that your output won't be confused with any special HTML characters. Eg:

$x = 'ggukjbgfjI:2<';
$y = 'EiK6';
$z = 'ggukjbgfjI:2<EiK6';
echo htmlspecialchars($x);
echo htmlspecialchars($y);
echo "<br><br>";
echo htmlspecialchars($z);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.