Skip to content

How to Escape Single Quotes for JavaScript in PHP

For example, if you have a button in PHP code like this:

...
return "<button onclick='get_name("$id", "$title")'>Post</button>";
...

It will work well except the following case containing a single quote:

...
$title = "You don't have to do that.";
return "<button onclick='get_name("$id", "$title")'>Post</button>";
...

The above code snippet will be interpreted as:

 <button onclick='get_name("32", "You don't have to do that.")'>Post</button>

This does NOT trigger JavaScript function "get_name()" on clicking.

I guess you may want to add an escape character "" before a single quote, but it does not work also. So our question is: What should we use to replace the single quote?

My finding is to use ' to replace the single quote. In our case, we should rewrite the code into:

...
$title = str_replace("'", "'", $title);
//or
$title = htmlentities($title, ENT_QUOTES);
return "<button onclick='get_name("$id", "$title")'>Post</button>";
...

We replaced the single quote with its symbol entity "'" by str_replace or htmlentities, then passed the string into the JavaScript event function. Yes, it's working now.

Not only str_replace(), you can also use htmlentities() to convert all applicable characters to HTML entities, including single quote. For more information about character entity, please refer to: List of XML and HTML character entity references.

Accepting arbitrary stings as inputs of JavaScript functions might not be a good practice. It make the function very unpredictable. So I think we should avoid to design functions in this manner.

Leave a Reply

Your email address will not be published.