Question

I'm getting a lot of text values from my database that I need to output with slashes added before characters that need to be quoted.

Problem is that some of the data already has the slashes added there from before, whilst some of it doesn't.

How can I add slashes using for example addslashes() - but at the same time make sure that it doesn't add an extra slash in the cases where the slash is already added?

Example:

Input: <a href="test.html">test</a>
Output should be: <a href=\"test.html\">test</a>

Input: <a href=\"test.html\">test</a>
Output should be: <a href=\"test.html\">test</a>

This is PHP 5.3.10.

Was it helpful?

Solution

If you know that you don't have any double slashes, simply run addslashes() and then replace all \\ with \.

OTHER TIPS

If you have something like this:

<a href=\"test.html\">test</a>

Using addslashes(), the output will be:

<a href=\\\"test.html\\\">test</a>

So, you may need to replace every occurrence of more than one \ to be sure

function addslashes($string) {
    return preg_replace('/([^\\\\])\"/','$1\"',$string);
}

The answer of Qaflanti is correct but I would like to make it more complete, if you want to escape both single and double quotes.

First option :

function escape_quotes($string) {
    return preg_replace("/(^|[^\\\\])(\"|')/","$1\\\\$2", $string);
}

Input

I love \"carots\" but "I" don't like \'cherries\'

Output

I love \"carots\" but \"I\" don\'t like \'cherries\'

Explanation :

The \ has a special meaning inside a quoted expression and will escape the following character in the string, so while you would need to write \\ in a regex to search for the backslash character, in php you need to escape those two backslashes also, adding up to a total of 4 backslashes.

So with that in mind, the first capturing group then searches for a single character that is not a backslash (and not two or four backslashes as misleading as it is)

The second capturing group will search for a double or a single quote exactly once.

So this finds unescaped quotes (double and single) and add a backslash before the quote thus escaping it.

Regex visual explanation

Second option :

Or it might just be best for you to convert them to html entities from the start :

function htmlentities_quotes($string) {
    return str_replace(array('"', "'"), array("&quot;", "&apos;"), $string);
}

And then you just have to use the php function htmlspecialchars_decode($string); to revert it back to how it was.

Input

I love "carots" but "I" don't like 'cherries'

Output

I love &quot;carots&quot; but &quot;I&quot; don&apos;t like &apos;cherries&apos;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top