March 7, 2012

PHP String – Escape Single Quotes (for jQgrid Select Box)

Question by FastTrack

I have a string:

$departmentList = "value:'16:NAR,JR'S OFFICE;17:MFR'S OFFICE;18:NAR/MFR JOINT OFFICE'"

My problem is, the single quotes you can see in JR'S OFFICE and MFR's OFFICE are prematurely ending my string. I could switch my double quotes with single quotes and vice versa, but these are coming from user-entered values. If the user had entered a double quote, I would be in the same boat as I am now.

Any ideas on how to keep the integrity of this string while having single and double quotes throughout?

By the way, not sure if this matters for anything but – I’m putting my $departmentList string into a jQGrid to build the values for a select box.

Answer by xato

Use addslashes to replace " with " and ' with '.

Answer by Starx

If you are using the input for database purpose better use mysql_real_escape_string()

$departmentList = "value:'16:NAR,JR'S OFFICE;17:MFR'S OFFICE;18:NAR/MFR JOINT OFFICE'";
$data = mysql_real_escape_string($departmentList);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!