3

Hi I was wondering if there is an easy way to escape strings in php.

In python I use """ """, and everything between there is escaped. so when using special characters it is ignored.

I have some text to echo, and escaping everything manually just takes forever.

Does php have a similar function built in ?

thanks!

Lucas Kauffman
  • 6,789
  • 15
  • 60
  • 86
  • I think I might got the question wrong. Do you have to `echo` an escaped version of the string or do you have to escape chars in the string to have a correct string? – Felix Kling Jul 02 '11 at 09:43

3 Answers3

7

Which are the characters do you have to escape?

You could use single quotes [docs]. The only characters that have to be escaped in such a string are \ and '.

If you have a long string, also have a look at heredoc [docs].

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
3

Since PHP 5.3, you can use nowdoc. As opposed to heredoc, nowdoc does not expand variables inside it.

rid
  • 61,078
  • 31
  • 152
  • 193
0

There are various functions depending on what you want to escape.

If you are using a lot of double quotes, for example with html, you can wrap the string in single quotes to prevent having to escape.

$string = '<a href="#">no escape needed</a>';

The same goes the other way

$string = "I'd rather be gaming";

Then you have a couple of functions used mostly for escaping user input:

addslashes() that will escape quotes
htmlspecialchars() will 'escape' html codes
mysql_real_escape_string() for escaping mysql input

Kokos
  • 9,051
  • 5
  • 27
  • 44