How to Strip All Spaces Out of a String in PHP

How do I strip all spaces out of a string in PHP?

Do you just mean spaces or all whitespace?

For just spaces, use str_replace:

$string = str_replace(' ', '', $string);

For all whitespace (including tabs and line ends), use preg_replace:

$string = preg_replace('/\s+/', '', $string);

(From here).

Remove excess whitespace from within a string

Not sure exactly what you want but here are two situations:

  1. If you are just dealing with excess whitespace on the beginning or end of the string you can use trim(), ltrim() or rtrim() to remove it.

  2. If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " ".

Example:

$foo = preg_replace('/\s+/', ' ', $foo);

Remove all spaces from a string that are not enclosed in singlequotes or doublequotes

You could capture either " or ' in a group and consume any escaped variants or each until encountering the closing matching ' or " using a backreference \1

(?<!\\)(['"])(?:(?!(?:\1|\\)).|\\.)*+\1(*SKIP)(*FAIL)|\h+

Regex demo | Php demo

Explanation

  • (?<!\\) Negative lookbehind, assert not a \ directly to the left
  • (['"]) capture group 1, match either ' or "
  • (?: Non capture group
    • (?!(?:\1|\\)). If what is not directly to the right is either the value in group 1 or a backslash, match any char except a newline
    • | Or
    • \\. Match an escaped character
  • )*+ Close non capture group and repeat 1+ times
  • \1 Backreference to what is captured in group 1 (match up either ' or ")
  • (*SKIP)(*FAIL) Skip the match until now. Read more about (*SKIP)(*FAIL)
  • | Or
  • \h+ Match 1+ horizontal whitespace chars that you want to remove

As @Wiktor Stribiżew points out in his comment

In some rare situations, this might match at a wrong position, namely,
if there is a literal backslash (not an escaping one) before a
single/double quoted string that should be skipped. You need to add
(?:\{2})* after (?<!\)

The pattern would then be:

(?<!\\)(?:\\{2})*(['"])(?:(?!(?:\1|\\)).|\\.)*+\1(*SKIP)(*FAIL)|\h+

Regex demo

How can strip whitespaces in PHP's variable?

A regular expression does not account for UTF-8 characters by default. The \s meta-character only accounts for the original latin set. Therefore, the following command only removes tabs, spaces, carriage returns and new lines

// http://stackoverflow.com/a/1279798/54964
$str=preg_replace('/\s+/', '', $str);

With UTF-8 becoming mainstream this expression will more frequently fail/halt when it reaches the new utf-8 characters, leaving white spaces behind that the \s cannot account for.

To deal with the new types of white spaces introduced in unicode/utf-8, a more extensive string is required to match and removed modern white space.

Because regular expressions by default do not recognize multi-byte characters, only a delimited meta string can be used to identify them, to prevent the byte segments from being alters in other utf-8 characters (\x80 in the quad set could replace all \x80 sub-bytes in smart quotes)

$cleanedstr = preg_replace(
"/(\t|\n|\v|\f|\r| |\xC2\x85|\xc2\xa0|\xe1\xa0\x8e|\xe2\x80[\x80-\x8D]|\xe2\x80\xa8|\xe2\x80\xa9|\xe2\x80\xaF|\xe2\x81\x9f|\xe2\x81\xa0|\xe3\x80\x80|\xef\xbb\xbf)+/",
"_",
$str
);

This accounts for and removes tabs, newlines, vertical tabs, formfeeds, carriage returns, spaces, and additionally from here:

nextline, non-breaking spaces, mongolian vowel separator, [en quad, em quad, en space, em space, three-per-em space, four-per-em space, six-per-em space, figure space, punctuation space, thin space, hair space, zero width space, zero width non-joiner, zero width joiner], line separator, paragraph separator, narrow no-break space, medium mathematical space, word joiner, ideographical space, and the zero width non-breaking space.

Many of these wreak havoc in xml files when exported from automated tools or sites which foul up text searches, recognition, and can be pasted invisibly into PHP source code which causes the parser to jump to next command (paragraph and line separators) which causes lines of code to be skipped resulting in intermittent, unexplained errors that we have begun referring to as "textually transmitted diseases"

[Its not safe to copy and paste from the web anymore. Use a character scanner to protect your code. lol]

How to remove spaces before and after a string?

You don't need regex for that, use trim():

$words = '      my words     ';
$words = trim($words);
var_dump($words);
// string(8) "my words"

This function returns a string with whitespace stripped from the beginning and end of str.

How to remove all white spaces if more than one

$str = preg_replace('/\s+/', ' ', $originalString);
echo $str;

This will replace all whitespace with a single space.

Remove the space between two words in PHP

'PaneerPakodaDish' should be the desired output.

$string = 'Paneer Pakoda dish';
$s = ucfirst($string);
$bar = ucwords(strtolower($s));
echo $data = preg_replace('/\s+/', '', $bar);

It will give you the exact output 'PaneerPakodaDish' where character "D" will also be in capital.



Related Topics



Leave a reply



Submit