Anyone who has coded html has come across this issue, you have an input field in your form but oh no! someone has entered a single or double quote into the value and they are now trying to edit it, and all you see in the input box is John\ instead of John\’s. It is one of those reoccuring issues which I face from time to time, but not anymore.

Every now and then i stumble across a new issue which my current method doesn’t solve. Talk about frustration, going through old code just to make sure you aren’t using that incorrect method. Heres something I whipped up tonight which I thought I should post asap.

function form_encode($string)
{
/*make sure you remove the spaces in the first variable of the str_replace function, Word press doesn't seem to like to print out the htmlentity of the ampersand which is understandable*/
return str_replace("& amp ;", "&", (htmlentities(stripslashes($string), ENT_QUOTES)));
}
I’m pleased with this solution, i’m hoping it’s not too computational intensive as it uses str_replace only once.

This function is especially effective when the data is being pulled from a database, but i found i needed a solution that can not only use data from a database and encode it properly but also if you are reusing $_POST variables, my forms if they fail reuse the same values, and i was getting alot of “John\ ” errors but using the stripslashes then the htmlentities fixed it up really nice.

The reason for the str_replace is the htmlentities function will change the ampersand at the start of some special characters into the htmlentity & amp ; which is what the function is supposed to do.. funny that. But a simple str_replace returns any double encoded htmlentites back into their original format, which means perfect display for us and easier forms from now on.

This has been tested on Firefox for Mac, Safara (Mac), will test on PC later. Thought I’d get this up asap for everyone. Will be interested to see if anyone finds it though.

Bookmark and Share