Escape single quote when a Javascript function call is rendered from PHP

I have many instances where I need to call a JavaScript function from a PHP generated html code. For example,

<a href="javascript: updateTitle('<?php echo $current_title;?>');">Update</a>

function updateTitle(title)
  var new_title = prompt('update title', title);
This works pretty well except if the $current_title variable contains a single quote, then it will result in javascript syntax error and the link will not work.

I tried several different approach to solve this issue but the best and the simplest solution that I found was to simply escape the single quote from PHP since the data is already being rendered from PHP code.

So the above code should be updated to:

<a href="javascript: updateTitle('<?php echo str_replace("'", "\\'", $current_title);?>');">Update</a>
However, if the $current_title variable contains a double quote then it will also result in syntax error but replacing the double quote with escaped double quote like above does not work in this case. For double quote, you will have to replace it with &quot;.
So I created utility helper method as follows:

// HandyUtils class
public static function escapeQuotes($string)
    $string = str_replace("'", "\\'", $string);
    $string = str_replace("\"", "&quot;", $string);

    return $string;
And the final code can be written as

<a href="javascript: updateTitle('<?php echo HandyUtils::escapeQuotes($current_title);?>');">Update</a>

I'm sure there may be better way to solve this issue but I couldn't get it to work using PHP's addslashes() or htmlspecialchars() functions...

Let me know if you find a better way to solve this issue. Thanks.
Go Back to List Page

Leave a comment

Name : Comment : view emoticons
Please consider signing up for our website.
If you sign up and log in:
  •   You can avoid the "I'm not a robot" captcha when commenting
  •   You can also avoid typing your name every time
  •   You can upload a picture for each comment
  •   You can change or delete your comment within 1 hour
  •   You can track all the comments you posted on this site
  •   You can read blog posts that are only open to members
  •   You can look up blogs using the search feature
  •   More privileges for our friends & families coming...

OK, Sign me up!

Emoticons are a great way to visually express how you feel.
However, there are times when unintended content is converted to emoticon because the content happens to have one of the emoticon symbols. That's why it's always good idea to preview your comment before posting and when you see this type of problem, you can indicate NOT to auto convert.