Sunday, August 28, 2016

Escaping Special Charactors in an HTML Form

Special characters, such as the apostrophe, can be pain. In the first image below note that the story name appears correct (in the title block) in one instance and truncated in the second instance (the data entry field). In both cases the very same variable was used to display the name of the story. So it was quite surprising to see this unexpected truncation.

Note: the unexpected truncation of "Venus is a Man's World" in the story name data entry field.
I have known about the need to escape certain character, such as the apostrophe, for a long time; but this is the first time where I have observed truncation in an HTML data entry field. Then again, I am new to HTML forms and HTML data entry techniques.

It took a bit of digging (since I am not used to using HTML) but once found; the solution was relatively easy to apply.  See bottom of page for some helpful links. As expected it was a simple replacement, but using an HTML entity.

 $storyname=str_replace("'", "&#39", $storyname);

The image below shows the effect of the code above. Note that this code is placed immediately before "Venus is a Man's World" is displayed on the HTML form's data entry field.

The unexpected truncation has been fixed.

There is a slight twist to using the code above. That is you may have to use the PHP functions "addslashes" and "stripcslashes" to get the data to upload to your database and/or display correctly on your HTML forms.  The example code below is a portion of the code used for uploading the revised data on the form to the database.


The "breakthrough" post that helped develop the solution above came from: "How to escape single quote". Additionally, from there is this helpful tutorial: "PHP str_replace() Function".