clean (function)

Last updated: Fri, Apr 14, 2023 5:12 pm
Return to Knowledgebase


Sanitizes a given string by removing special characters and replacing spaces with hyphens.




# Parameter Data Type Required Description
1 $string string Yes The string you wish to sanitize

Further Documentation:

The function takes one parameter: $string, which is the string to sanitize.

The function first replaces all spaces in the string with hyphens using the str_replace() function.

The function then removes any special characters from the string using the preg_replace() function with a regular expression that matches any non-alphanumeric character.

Finally, the function replaces any consecutive hyphens in the string with a single hyphen using another preg_replace() call.

This function can be useful in cases where you need to sanitize user input or generate slugs (URL-friendly versions of strings) for use in URLs or file names.

// Sanitize user input and generate a slug
$userInput = "Hello, World! This is a test.";
$slug = clean($userInput);

// Display the sanitized input and slug
echo "User input: ".$userInput."
echo "Slug: ".$slug;

In this example, we call the "clean" function with a test string containing special characters and spaces. The function sanitizes the string by removing the special characters and replacing the spaces with hyphens. We then display the original input and the resulting slug to show how the function works. The resulting output might look something like this:

User input: Hello, World! This is a test.
Slug: hello-world-this-is-a-test

Note that the resulting slug is all lowercase and contains no special characters or spaces, making it safe to use in URLs or file names. However, be aware that this function may not be appropriate for all use cases, such as when special characters or spaces are needed in the output.