PHP - addcslashes() Function



The PHP addcslashes() function is used to retrieve an escaped string with backslashes before characters that are listed in the character parameter.

An "escaped" string is a string that uses escape sequences (preceded by a backslash \) to represent special characters. For example, \n for a newline and \" for a quote.

This function accepts a parameter as a list of characters. If the character list contains characters like '\n', '\r', etc., they are converted in a "C-like" style. Additionally, any non-alphanumeric characters with ASCII codes lower than "32" and higher than "126" are converted to octal representation.

Syntax

Following is the syntax of the PHP addcslashes()) function −

addcslashes(string $str, string $characters): string

Parameters

This function accepts two parameters are listed below −

  • str − This string to be escaped.
  • characters − The list of characters to be escaped.

Return Value

This function returns a escaped string.

Example 1

Escaping specific characters in a string.

The following is a basic example of the PHP addcslashes() function −

<?php
   $str = "Tutorialspoint";
   echo "The given string is: $str";
   $chars = "ia";
   echo "\nThe give list of chars: $chars";
   #using addcslashes() function
   echo "\nThe escaped string: ".addcslashes($str, $chars);
?>

Output

The above program produces the following output −

The given string is: Tutorialspoint
The give list of chars: ia
The escaped string: Tutor\i\alspo\int

Example 2

Escaping all the uppercase letters in a string.

Here is another example of the PHP addcslashes() function. This function is used to retrieve the escaped string by escaping all the uppercase letters in a string "Hello World" −

<?php
   $str = "Hello World";
   echo "The given string is: $str";
   #using addcslashes() function
   echo "\nThe escaped string: ".addcslashes($str, 'A..Z');
?>

Output

After executing the above program, the following output will be displayed −

The given string is: Hello World
The escaped string: \Hello \World

Example 3

Escaping all lowercase and uppercase letters in a string.

In the example below, we use this property to escape all lowercase and uppercase letters in the returned string −

<?php
   $str = "Welcome to [Tutorialspoint]";
   echo "The given string is: $str";
   #using addcslashes() function
   echo "\nThe escaped string: ".addcslashes($str, 'A..z');
?>

Output

Following is the outout of the above program −

The given string is: Welcome to [Tutorialspoint]
The escaped string: \W\e\l\c\o\m\e \t\o \[\T\u\t\o\r\i\a\l\s\p\o\i\n\t\]
php_function_reference.htm
Advertisements