Skip to content
Prem Tiwari
  • WP Tutorials
  • Plugins
  • About Me
  • Featured On
  • Let’s Talk
Prem Tiwari
Home / PHP / How to Remove all special characters including white space in PHP

How to Remove all special characters including white space in PHP

ByPrem Tiwari Last updated onJuly 26, 2024

To remove all special characters, including whitespace and multiple spaces, in PHP, you can use a combination of preg_replace() to remove unwanted characters and trim() to handle leading and trailing spaces. Here’s a step-by-step guide:

Step-by-Step Guide

  1. Remove all special characters:
    • Use preg_replace() with a pattern that matches any character that is not a letter or a digit.
  2. Remove multiple spaces:
    • Use preg_replace() again to replace multiple spaces with a single space.
  3. Trim the string:
    • Use trim() to remove leading and trailing spaces.

Here’s a sample function that demonstrates this:

<?php

function cleanString($input) {
    // Step 1: Remove all special characters except letters and digits
    $cleaned = preg_replace('/[^A-Za-z0-9 ]/', '', $input);
    
    // Step 2: Replace multiple spaces with a single space
    $cleaned = preg_replace('/\s+/', ' ', $cleaned);
    
    // Step 3: Trim leading and trailing spaces
    $cleaned = trim($cleaned);
    
    return $cleaned;
}

// Example usage
$input = " Hello, World! This is a    test. ";
$output = cleanString($input);

echo $output; // Output: "Hello World This is a test"

?>

Example Input and Output

  • Input: " Hello, World! This is a test. "
  • Output: "Hello World This is a test"

By using the above function, you can ensure that your string is free of special characters, multiple spaces, and unnecessary leading or trailing spaces.

Found it helpful? Share it with your friends on social media!

  • Facebook
  • Post on X
  • LinkedIn
Prem Tiwari

Prem Tiwari is a passionate advocate of open source technology, with over 10+ years of experience in the WordPress domain. He has great experience when it comes to scaled WordPress projects which caters the need for big enterprise clients on WordPress and WordPress VIP-GO platform.

Facebook Twitter Instagram YouTube Linkedin

Post navigation

Previous Previous
Disable Features – All-in-One plugin to disable unnecessary features
NextContinue
Moderated a WordPress Security at WordCamp Bengaluru 2024

Collections

  • Crawling and indexing
  • Meetup
  • PHP
  • Plugins
  • SEO
  • Tech Talks
  • WooCommerce Tutorials
  • WordCamp
  • WordPress Tutorials
  • Privacy
  • Cookies
  • Disable Update Notifications
Facebook Twitter Instagram YouTube Linkedin WordPress
Scroll to top
  • WP Tutorials
  • Plugins
  • About Me
  • Featured On
  • Let’s Talk