Search code examples
phphtml-encodephp-5.4

Html encode variable in quoted string


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));

Solution

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