Concat question when using htmlspecialchars

$firstName = “Bénny”;
$lastName = “O’Drärön”;

print (“<input name=‘myData’ type=‘text’ value='”.htmlspecialchars($firstName)." “.htmlspecialchars($lastName).”'>");


Bénny O

Apparently I am doing something wrong with the concatenation. Do you see anything amiss?


I don’t think you are doing anything wrong. It is the apostrophe in the last name. Try escaping it like below, and see if that helps.

$lastName = "O\\'Drärön";

Yes, but htmlspecialchars is supposed to handle slashes. I think the problem has something to do with the way I have done the concat. For whatever reason, the following version works. However, I was trying to do with single quotes instead of double quotes:

print ("<input name=\\"myData\\" type=\\"text\\" size=\\"30\\" maxlength=\\"40\\" value=\\"".htmlspecialchars($firstName)." ".htmlspecialchars($lastName)." \\">");

I understand, that is why I posted that code. By trying to use single quotes, it was interpreting the apostrophe in the last name. Allow me to interpret how PHP was interpreting your code:

' " Bénny O';

Do you see it now? PHP was interpreting the apostrophe as an end point of parsing the data.

busboy, I don’t see anything wrong in the code you posted. And I copy-pasted it, and it ran just fine for me. That should mean that the real issue is elsewhere in the code you haven’t posted.

The answer to this I believe lies in PHP’s htmlspecialchars options.

By default, htmlspecialchars will NOT convert ’ into the HTML entity . This is the default (ENT_COMPAT) mode.

So when you execute your code as written, your output would be:

<input name='myData' type='text' value='B#233;nny O'Dr#228;r#246;n'>

Note the coloring, and you’ll see why you got what you did.

If you want apostrophes to be converted, you’ll have to specify that flag when you call htmlspecialchars;

This will convert both " and ’ to their HTML Entities.

(EDIT: Yeah, and SP wont let me put in the special characters lol. I’ve removed the &'s in front of them to make it not-translate, but you get the picture.

Whoops. Good catch, StarLion.

If you put & on the front of entity codes as you enter them the & should display without converting the codes - or simply specify the code outside of a code box and it will not get converted at all.