PHP addcslashes() Function
Topic: PHP String ReferencePrev|Next
Description
The addcslashes()
function returns a string with backslashes before the specified characters.
The following table summarizes the technical details of this function.
Return Value: | Returns the escaped string |
---|---|
Changelog: | The escape sequences \v and \f were added in PHP 5.2.5 |
Version: | PHP 4+ |
Syntax
The basic syntax of the addcslashes()
function is given with:
The following example shows the addcslashes()
function in action.
Example
Run this code »<?php
// Sample string
$str = "Hello World!";
// Escaping string
echo addcslashes($str, "!");
?>
Note: Be careful if you choose to escape characters 0, a, b, f, n, r, t and v. They will be converted to predefined escape sequences \0
(NULL byte), \a
(audible bell), \b
(backspace), \f
(form feed), \n
(newline), \r
(carriage return), \t
(tab), and \v
(vertical tab), respectively.
Parameters
The addcslashes()
function accepts the following parameters.
Parameter | Description |
---|---|
string | Required. Specifies the string to be escaped. |
charlist | Required. Specifies a list or a range of characters to be escaped. |
More Examples
Here're some more examples showing how addcslashes()
function actually works:
The following example demonstrates how to escape multiple characters.
Example
Run this code »<?php
// Sample string
$str = "Hello World!";
// Escaping string
echo addcslashes($str, "ol");
?>
The following example demonstrates how to define a sequence of characters to be escaped.
Example
Run this code »<?php
// Sample string
$str = "Jack and Jill Went Up The Hill";
// Escaping string
echo addcslashes($str, "A..Z")."<br>";
echo addcslashes($str, "a..z");
?>
Note: If the first character in a range has a higher ASCII value than the second character in the range, no range will be constructed. Only the start, end and period characters will be escaped. You can use the ord()
function to find the ASCII value of a character.
In the following example only z, A and period characters in the string will be escaped.
Example
Run this code »<?php
// Sample string
$str = "Alice saw many animals at the zoo.";
// Escaping string
echo addcslashes($str, "z..A");
?>