Escape Quotation in PHP

This article will introduce different methods to escape quotation in PHP.

Use the Backslash to Escape Quotation in PHP

Whenever we use quotation marks inside a string, the PHP compiler shows an error. To avoid this error, we will use backslash \ to escape it. The correct syntax to use backslash is as follows.

$mystring = "\"\"";

The output will be "".

The program below shows the way by which we can use the backslash \ to escape quotation marks in PHP.

<?php
echo("My name is \"DelftStack\".");
?>

Output:

My name is "DelftStack".

We can use the built-in function addslashes() to add backslashes using PHP. The correct syntax to use this function is as follows.

addslashes($string);

The detail of the parameter is as follows.

Variables Description
$string It is the string with which we want to add backslashes before the characters that generate the error.

The program below demonstrates further.

<?php
$string = "My name is "DelftStack"";
$newString = addslashes($string);
echo($newString);
?>

Output:

My name is "DelftStack".
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.