11 March 2024

In PHP, the task of stripping double whitespace while retaining only one space involves utilizing regular expressions or string manipulation functions. The regular expression /\\s+/ serves as a key component for this task. It's constructed with forward slashes to delimit the expression, \s to represent any whitespace character, and the + quantifier to match one or more consecutive whitespace characters. When employed with the preg_replace function, this regular expression searches for sequences of double whitespace and replaces them with a single space. This process effectively condenses multiple consecutive whitespace characters into a single space, achieving the desired outcome of preserving the text's content while eliminating redundant whitespace.

Source code viewer
  1. $string = "This is a string with double spaces";
  2. $cleaned_string = preg_replace('/\s+/', ' ', $string);
  3. echo $cleaned_string;
  4. // Output: "This is a string with double spaces"
Programming Language: PHP