Web Info and IT Lessons Blog...

Wednesday 10 December 2014

How to add backslashes in php?

The previous lesson of PHP Lessons Series was about Explode and Implode functions in PHP and in this lesson we will learn about Add Slashes Functions in PHP.

Add Slashes Functions in PHP

addcslashes()

Addcslashes function is used to add backslashes in front of defined characters of a string. The basic structure of addcslashes() function is given below:



$str = addcslashes(string, defined characters);


Defined characters in the above addcslashes() function can be a single character or multiple characters. addcslashes() function will add a backslash before each occurence of the defined characters. An example of addcslashes() function is given below:



$str = addcslashes("My Message is Hello World.","H");
echo($str); 


The above addcslashes() function will add a backslash before each occurence of the character 'H' in the string 'My Message is Hello World.'. The output of the above code is given below:

Output:
My Message is \Hello World.

If we want to add backslashes before more than one characters, then we will have to define more characters in the addcslashes() function. An example of defining more characters in addcslashes() function is given below:



$str = addcslashes("My Message is Hello World.","MseWrl");
echo($str); 


The above addcslashes() function will add a backslash before each occurence of the characters 'MseWrl' in the string 'My Message is Hello World.'. The output of the above code is given below:

Output:
\My \M\e\s\sag\e i\s H\e\l\lo \Wo\r\ld.

addslashes()

Addslashes function is used to add backslashes in front of certain pre-defined characters. The basic structure of addslashes() function is given below:



$str = addslashes(string);


If you pass a string in the above addslashes() function, backslashes will be added in front of pre-defined characters like ("") used in the string. An example code of addslashes() function is given below:


$str = addslashes('"Hello World"');
echo($str); 

The above addslashes() function will add backslashes in front of the characters "" in the the string "Hello World". The output of the above code is given below:

Output:
\"Hello World\"

Related Posts
How to remove backslashes in php?
Explode and Implode functions in PHP
PHP String Functions
More about PHP String Functions
PHP String Conversion Functions
PHP String Comparison Functions

No comments:

Post a Comment