How to escape quotes in PHP?

by scotty_walker , in category: PHP General , 2 years ago

How to escape quotes in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by darion , 2 years ago

@scotty_walker use addslashes() function to escape quotes in PHP, code:


1
2
3
4
5
6
<?php

$str = "How to 'escape quotes' in PHP?";

// Output: How to \'escape quotes\' in PHP?
echo addslashes($str);


Member

by gilbert , 10 months ago

@scotty_walker 

In PHP, you can escape single quotes ('), double quotes ("), and backslashes () by using a backslash () before the character.


Here are some examples:

  1. Escape single quotes within single quotes: $str = 'This is an example of escaping a single quote: ''; echo $str; Output: This is an example of escaping a single quote: '
  2. Escape double quotes within double quotes: $str = "This is an example of escaping a double quote: ""; echo $str; Output: This is an example of escaping a double quote: "
  3. Escape backslashes: $str = "This is an example of escaping a backslash: \"; echo $str; Output: This is an example of escaping a backslash:


By using the backslash () before the character, PHP treats it as a literal character instead of special characters.