OneBite.Dev - Coding blog in a bite size

Escape A String In PHP

Code snippet for how to Escape A String In PHP with sample and detail explanation

In this article, we will dive into the process of escaping a string in PHP. We will follow a step-by-step tutorial, aiming to make this significant task as digestible as possible for beginners.

Code snippet for Escaping a String in PHP

To escape a string in PHP, you can make use of either addcslashes() or addslashes() functions. For this tutorial, we will use the addslashes() function.

Here is a simple example:

<?php
$unescaped_string = "Hello World, I'm learning PHP.";
$escaped_string = addslashes($unescaped_string);
echo $escaped_string;
?>

Code Explanation for Escaping a String in PHP

Breaking down the code line by line:

  1. The PHP code block initiates with <?php, and similarly ends with ?>.
<?php
// PHP code goes here
?>
  1. The second line declares a variable $unescaped_string and assigns it a string value “Hello World, I’m learning PHP.”.
$unescaped_string = "Hello World, I'm learning PHP.";
  1. In the third line, another variable $escaped_string is put in place. Here it gets assigned the result of the addslashes() function when applied to our initial string $unescaped_string.
$escaped_string = addslashes($unescaped_string);

The function addslashes() in PHP is responsible for escaping any existing special characters in a given string, such as single quote (’), double quote (”), backslash (), and NULL.

  1. Lastly, the echo statement is a PHP language construct utilized to output one or more strings. Here, it outputs the escaped string.
echo $escaped_string;
?>

As a result, the output will be “Hello World, I’m learning PHP.”. Note the backslash before the single quote, this indicates that the single quote is escaped.

And that’s it! Now you know how to escape a string in PHP. Keep practicing and exploring to gain a better understanding. Happy Coding!

php