Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape quotes in a variable with PHP

Tags:

javascript

php

I use this code to genefate html

echo "<input type='button' onclick=\"myFunc('$param');\" />";

Everything would be OK unless $param contains ' or " character. How should it be implemented to handle these situations?

ps. mysql_real_escape_string($param) won't work correctly, when a user entered ".

like image 971
Alexander Avatar asked Apr 16 '11 11:04

Alexander


People also ask

How do you put quotes around a variable in PHP?

echo "\"$animal\""; Or you can just use single quotes instead as the following: echo '"$animal"'; Whichever you prefer.

How do you escape a quotation mark?

'Remember to say "please" and "thank you."'; Alternatively, you can use a backslash \ to escape the quotation marks.

How can I add double quotes to a variable in PHP?

Just escape them: echo "\"$time\""; You could also use single around the double quotes: echo '"' .


1 Answers

There are a couple of functions that could be used:

<?php
$string = 'string test"';

echo htmlentities($string) . "\n";
echo addslashes($string) . "\n";

They produce the following:

string test&quot;
string test\"
like image 152
Nick Avatar answered Sep 28 '22 10:09

Nick