Escaping Double Quotes in PHP (Wordpress)

3.1k views Asked by At

I'm having difficulties escaping double quotes using the PHP addslashes function. If I run:

$name = addslashes(get_the_title());

And the title has double quotes in it, the output still has double quotes without any escape characters.

eg. “Welcoming Diversity” Immigration Forum

I'm trying to insert Wordpress data into an .ICS file generator, but I'm unable to find a way to successfully parse the Wordpress data into a format that co-operates with the ICS format.

SOLUTION: My solution was to bypass the Wordpress function get_the_title() by using $post->post_title instead. Escaping worked properly with addslashes once I switched.

3

There are 3 answers

1
José Fernández Ramos On

Maybe trim helps (for scaping regular quotes):

$name = addslashes(trim(get_the_title(), '"'));

For other kind of quotes you could try using regular expressions. Something like:

$title = preg_replace("/[\'\"\”\“]+/";, '', get_the_title());
$name = addslashes($title);
0
DaveRandom On

If the quotes are not getting escaped they are not true double quotes. It may be that your string is in a multibyte charset, or they are "fancy quotes".

This function often sorts this out:

function convert_fancy_quotes ($str) {
  return str_replace(array(chr(145),chr(146),chr(147),chr(148),chr(151)),array("'","'",'"','"','-'),$str);
}

So try:

$name = addslashes(convert_fancy_quotes(get_the_title()));

...although if this is the problem, they probably don't need escaping anyway, depending on what you are doing with the result.

0
Robbie McAlister On

The curly quotes is definitely something to check for. You also might want to check the expected input of function you're sending to. The addslashes() function will definitely add the escape characters, but if you're sending that output into another function that removes them, that could make it appear that the slashes aren't being escaped.