Syed Aun
Syed Aun

Reputation: 89

Error due to using single quotes in htmlspecialchars and htmlentities in php

Well it is pretty much straight forward to encode or skip different html characters by using:

echo htmlspecialchars('<b>"name"</b>', ENT_QUOTES).'<br>';

or

echo htmlentities('<b>"name"</b>', ENT_QUOTES).'<br>';  

These both statements work fine. But when I add single quotes '' inside the string like:

echo htmlspecialchars('<b>"'name'"</b>', ENT_QUOTES).'<br>';

or

echo htmlentities('<b>"'name'"</b>', ENT_QUOTES).'<br>';  

Then in such case it gives an error. Here I need to allow these single quotes inside that string. Please show me how to make allow the single quotes '' inside string.

Upvotes: 2

Views: 822

Answers (1)

Sebastian Brosch
Sebastian Brosch

Reputation: 43604

You have to escape the ' with \. So try the following solution:

echo htmlspecialchars('<b>"\'name\'"</b>', ENT_QUOTES).'<br>';
echo htmlentities('<b>"\'name\'"</b>', ENT_QUOTES).'<br>';

The other way using " for parameter would look like the following:

echo htmlspecialchars("<b>\"'name'\"</b>", ENT_QUOTES).'<br>';
echo htmlentities("<b>\"'name'\"</b>", ENT_QUOTES).'<br>'; 

Upvotes: 3

Related Questions