PHP addslashes() Function

Last Updated on July 23, 2021 by Roshan Parihar

PHP addslashes() Function is used to add backslashes (\) before the predefined character of a string. You don’t need to specify any characters to insert a backslash in front of it.

The predefined characters are:

  1. Single quote (‘)
  2. Double quote (“)
  3. Backslash (\)
  4. Null

Syntax of PHP addslashes() Function

addslashes(string)

The function takes a single argument as a string or string variable to add backslashes in PHP.

Description of Parameters

Name Description
string Required. It is the string to be escaped and add backslashes in front of predefined characters. The predefined characters are given above.

Let’s see some useful examples to easily understand the use of the PHP addslashes() Function.

Examples of PHP addslashes() Function

Here are examples to learn the function.

Example 1: Single quotes (‘) character

If the string contains single quotes, you can escape them using the PHP addcslashes() Function as given in the example below.

Output

Hello World\’s

The output shows that the string escaped a single quote (‘) of the given string in PHP. The example contains a string with a single quote (‘) that comes for a single time. However, if the string contains single quotes (‘) for more times, the function escapes all of them.

Example 2: Escape double quotes (“) characters

Similarly, it also escapes the double quotes (“) present in a string using the PHP addslashes() function. You can see the example given below to check the result:

Output

Welcome to \”TutorialDeep\”

The above example escapes double quotes (“) that come for more than one time in a string. Likewise, the above example can also escape double quotes (“) that come for more times in a string in PHP.

Example 3: Safe and Unsafe for Databases using the PHP addcslashes() Function

If the string contains single quotes (‘) and double quotes (“), it is not safe for the database query in PHP. However, you can make it safe using the PHP addcslashes() Function. So, you can use the function to convert the unsafe string to safe as given below:

Output

PHP Learner’s (This is not safe in a database query)
PHP Learner\’s (This is safe in a database query)

The first result contains the string without escaping the single quote. However, the second result in the above output escaped the single quote that makes it safe for the database query in PHP.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.