Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string doesn't allow < and > characters

Tags:

string

php

I have a string in my code as per the following example:

<?php
$find = '<tag';
$string = 'blah blah <tag=something>';
?>

Simple enough, but when I try to echo the strings, it's not liking the < or > characters. All that get's echo'ed is:

blah blah

So, basically i'm guessing I need to escape these characters to get them to work in PHP but im not sure exactly how. I'm using this for a templating system, so in the html file a file can be included by using:

<include="filename.html">

So I don't need to show the < and > characters on the screen at any time, I just need to read the file, find the instances of these tags and do some magic. I've got all of that part working but It's just any string that contains more than / less than operators that don't seem to work OK.

Any ideas?

like image 679
Amo Avatar asked Nov 21 '11 03:11

Amo


1 Answers

With PHP you can generate HTML markup, so you have to find a way to distinguish between HTML element characters ( < & > ). There exist special sequence of characters in HTML that are called HTML entities. Those are described with an ampersand, some sort of shorthand and end with a semi-colon.

Here are some examples:

&gt;     : > (greater-than)
&lt;     : < (less-than)
&amp;    : & (ampersand)
&raquo;  : » (right angle quote marks)
&eacute; : é (e acute)

Almost all characters can be represented with such entities, but it quickly gets tedious. You only have to remember the < and > ones, plus the & for URLs.

Your code should be rewritten like this if your intention was to show the less-than / greater-than signs.

<?php
$find = '&lt;tag';
$string = 'blah blah &lt;tag=something&gt;';
?>

As mentioned in other answers, you can use the function htmlspecialchars() to convert characters in a variable (e.g. from user input).

<?php echo htmlspecialchars($string); ?>

will display blah blah <tag=something> for viewing in a web browser. Else, if you were using PHP on the command line for example, you would not need to use this function.

like image 147
sleblanc Avatar answered Sep 28 '22 07:09

sleblanc