Example of recursive escape of the addslashes array in php

Source: Internet
Author: User
Tags foreach

I. Functions mainly involve the addslashes method.

The addslashes () function adds a backslash before the specified predefined character.

The predefined characters are:

• Single quotes (')
• Double quotation marks (")
• Backslash (\)
• NULL

II. array_map description

The array_map () function returns the array after the user-defined function is applied. The number of parameters accepted by the callback function should be the same as the number of arrays passed to the array_map () function.
If the passed parameters are in the array format, use the array_map method to escape the parameters.


We are developing variables such as $ _ GET and $ _ POST.

The code is as follows: Copy code

/**
* Recursively escape special characters in a variable
 *
* @ Access public
* @ Param mix $ value
 *
* @ Return mix
*/
Function addslashes_deep ($ value)
{
If (empty ($ value ))
 {
Return $ value;
 }
Else
 {
Return is_array ($ value )? Array_map ('addslashes _ deep ', $ value): addslashes ($ value );
 }
}

If it is an array, the security escape cannot be completed. The following is an example. Let's take a look.


Method 3,You can refer to this recursive method to implement other functions. The code is as follows:

The code is as follows: Copy code

<? Php
$ Arr = array ('a "AA', array (" c 'd ", array ('E" f ')));
Function changes ($ arr ){
Foreach ($ arr as $ k =>$ v ){
If (is_string ($ v )){
$ Arr [$ k] = addslashes ($ v );
} Else if (is_array ($ v) {// escape if it is an array.
$ Arr [$ k] = changes ($ v );
  }
 }
Return $ arr;
}
Print_r (changes ($ arr ));
?>
The input result is as follows:

Array
(
[0] => a \ "aa
[1] => Array
        (
[0] => c \ 'd
[1] => Array
                (
[0] => e \ "f
                )

        )

)

The principle is very simple, that is, to use foreach to traverse the array values.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.