1

In PHP5.4, is it possible to html encode (using htmlspecialchars) a variable being used in a quoted string?

For instance, is it possible to format the following so that $title is automatically encoded by PHP?

echo "<h1>$title</h1>";

In ASP.NET (my normal development technology) I can write an inline code block like <%=title%>, but if I want to html encode title then all I have to do is write the block like <%:title%>.

I realise the following are ways to do it, but they are "messy" and less readable in comparison...

echo '<h1>' . htmlspecialchars($title) . '</h1>';
printf('<h1>%s</h1>', htmlspecialchars($title));
freefaller
  • 19,368
  • 7
  • 57
  • 87
  • 1
    How do you mean *automatically* ? Just encode it and assign it – Rizier123 Apr 04 '15 at 09:42
  • Good point @Rizier, I guess I've not made that clear... will update the question – freefaller Apr 04 '15 at 09:45
  • I don't think this is possible in PHP to apply automatically a function to all variables which you print – Rizier123 Apr 04 '15 at 09:58
  • That was my assumption @Rizier - I'm getting my teeth back into PHP for the first time in years, so am not up to speed with all the latest features of PHP5 – freefaller Apr 04 '15 at 10:04
  • No. You can't have htmlspecialchars() automatically applied to variables in PHP. But, if you use any MVC framework, for example CI, Yii, it is not hard to override view's classes that will do it when you pass variables from controller to view. Another solution - wrap function with you own function, for example with "hm" as name, and then write hm($var) - it will shorter and quicker. – Alexander R. Apr 06 '15 at 13:19

1 Answers1

1

The shortest and ASP.NET like way is: <h1><?= htmlspecialchars($title) ?></h1>

Peter Petrov
  • 435
  • 5
  • 7