"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Replace Multiple Spaces with a Single Space After `ereg_replace` Is Deprecated?

How Can I Replace Multiple Spaces with a Single Space After `ereg_replace` Is Deprecated?

Published on 2024-11-06
Browse:280

How Can I Replace Multiple Spaces with a Single Space After `ereg_replace` Is Deprecated?

Replacing Multiple Spaces with a Single Space: Deprecating ereg_replace

While using ereg_replace to replace multiple spaces with a single space may seem straightforward, it has been deprecated. Consequently, you may encounter errors when attempting to utilize it. This article presents an alternative solution.

Migration to preg_replace()

To replace ereg_replace, switch to preg_replace(). Instead of employing the [ \t\n\r] pattern, which matches multiple spaces, tabs, newlines, and carriage returns, use \s . This shorthand character class encompasses all whitespace characters, effectively replacing multiple spaces with a single space.

Code Example

Implement the following code to achieve the desired result:

$output = preg_replace('!\s !', ' ', $input);

Explanation

  • preg_replace('!\s !', ' ', $input) scans the $input string for multiple whitespace characters using the \s pattern.
  • It replaces any sequence of consecutive whitespace characters with a single space, producing the $output string.

Additional Resource

Refer to the Regular Expression Basic Syntax Reference for further clarification on \d, \w, and \s character classes:

https://www.php.net/manual/en/regexp.reference.basic-syntax.php

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3