Using WordPress ‘deslash()’ PHP function

The deslash() WordPress PHP function filters content to remove unnecessary slashes.

Usage

Here’s a straightforward usage of deslash() function:

$raw_content = "I\'m a text with extra slashes. Let\'s clean it!";
$clean_content = deslash($raw_content);
echo $clean_content;

In this example, the output will be: “I’m a text with extra slashes. Let’s clean it!”

Parameters

  • $content (string – required): The content you want to modify or clean from unnecessary slashes.

More information

See WordPress Developer Resources: deslash()

Please note that this function is used to sanitize content, making it cleaner and safer for display or storage.

Examples

Cleaning up a string

We are cleaning up a simple string.

$messy_string = "Slash\\es can \\be \\annoying!";
$clean_string = deslash($messy_string);
echo $clean_string; // Output: "Slashes can be annoying!"

Removing slashes in an array

Here, we’re removing slashes from all items in an array.

$messy_array = array("I\\'m\\ a\\ string", "So\\ am\\ I");
$clean_array = array_map('deslash', $messy_array);
print_r($clean_array); // Output: Array ( [0] => "I'm a string", [1] => "So am I" )

Cleaning content in a form input

In this scenario, we’re sanitizing a form input to prevent potential security issues.

$form_input = $_POST['form_input'];
$clean_input = deslash($form_input);
// Now, $clean_input is safe to use for display or database storage

Cleaning up a URL

Unnecessary slashes in a URL can lead to issues. Here’s how to clean them.

$url = "https:\\/\\/www.example.com\\/path\\/to\\/page";
$clean_url = deslash($url);
echo $clean_url; // Output: "https://www.example.com/path/to/page"

Cleaning JSON data

We’re going to clean a JSON string from unnecessary slashes.

$messy_json = "{\\"name\\": \\"John\\", \\"age\\": 30}";
$clean_json = deslash($messy_json);
echo $clean_json; // Output: '{"name": "John", "age": 30}'