Page 1 of 1

how to escape my database content?

Posted: Sun Jan 23, 2005 10:44 am
by jasongr
Hello

I have some string which I get from the database called $string
I need to pass this string to a javascript function like so:

Code: Select all

<a href="#" onclick="func('<?php echo $string; ?>');">test</a>
The problem here is that the string may contain any character including single or double quotes. This will cause a JavaScript error if not handled properly

I was wondering what would be the correct and robust way to escape the string so it won't interfere with string escaping in HTML and JavaScript

regards

Posted: Sun Jan 23, 2005 10:48 am
by feyd
urlencode would work quite well..

then use the JS function unescape() to translate it back.

Posted: Sun Jan 23, 2005 10:58 am
by jasongr
I tried you solution on the string
John Smith
and urlencode gave me
John%2C+Smith

when I invoked unescape on it I got John+Smith
How can I get rid of the '+' character that won't go away?

Posted: Sun Jan 23, 2005 11:07 am
by feyd

Code: Select all

$string = str_replace('+','%20', urlencode('John, Smith');