"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 use Regular Expressions to match spaces in PHP?

How can I use Regular Expressions to match spaces in PHP?

Published on 2025-01-25
Browse:354

How can I use Regular Expressions to match spaces in PHP?

Matching Spaces with Regular Expressions in PHP

Finding space characters in a PHP regular expression can be done in several ways.

Single Space:
To match a single space, use " ":

preg_replace('/[ ]/', '', $tag);

Multiple Spaces:
To match one or more spaces, use " *":

preg_replace('/[ ] /', '', $tag);

Whitespace:
To match any whitespace, including tabs, use "\s":

preg_replace('/[\s]/', '', $tag);

Word Boundaries:
To match the start or end of a word where spaces are common, use "\b":

preg_replace('/\b[ ]\b/', '', $tag);

Remove Non-Valid Characters:
To remove all non-valid characters, leaving only letters, numbers, and spaces, use:

preg_replace('/[^a-zA-Z0-9 ]/', '', $tag);

Multiple Spaces between Words:
To remove multiple spaces between words while preserving single spaces, perform a series of replacements:

$newtag = preg_replace('/  /', ' ', $tag);
$newtag = preg_replace('/^ /', '', $newtag);
$newtag = preg_replace('/ $/', '', $newtag);

Note: The removal of spaces from the start and end is only necessary if the string may contain leading or trailing spaces.

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