[php] How can strip whitespaces in PHP's variable?

I know this comment PHP.net. I would like to have a similar tool like tr for PHP such that I can run simply

tr -d " " ""

I run unsuccessfully the function php_strip_whitespace by

$tags_trimmed = php_strip_whitespace($tags);

I run the regex function also unsuccessfully

$tags_trimmed = preg_replace(" ", "", $tags);

This question is related to php string whitespace

The answer is


Any possible option is to use custom file wrapper for simulating variables as files. You can achieve it by using this:

1) First of all, register your wrapper (only once in file, use it like session_start()):

stream_wrapper_register('var', VarWrapper);

2) Then define your wrapper class (it is really fast written, not completely correct, but it works):

class VarWrapper {
  protected $pos = 0;
  protected $content;
  public function stream_open($path, $mode, $options, &$opened_path) {
    $varname = substr($path, 6);
    global $$varname;
    $this->content = $$varname;
    return true;
  }
  public function stream_read($count) {
    $s = substr($this->content, $this->pos, $count);
    $this->pos += $count;
    return $s;
  }
  public function stream_stat() {
    $f = fopen(__file__, 'rb');
    $a = fstat($f);
    fclose($f);
    if (isset($a[7])) $a[7] = strlen($this->content);
    return $a;
  }
}

3) Then use any file function with your wrapper on var:// protocol (you can use it for include, require etc. too):

global $__myVar;
$__myVar = 'Enter tags here';
$data = php_strip_whitespace('var://__myVar');

Note: Don't forget to have your variable in global scope (like global $__myVar)


The \s regex argument is not compatible with UTF-8 multybyte strings.

This PHP RegEx is one I wrote to solve this using PCRE (Perl Compatible Regular Expressions) based arguments as a replacement for UTF-8 strings:

function remove_utf8_whitespace($string) { 
   return preg_replace('/\h+/u','',preg_replace('/\R+/u','',$string)); 
}

- Example Usage -

Before:

$string = " this is a test \n and another test\n\r\t ok! \n";

echo $string;

 this is a test
 and another test
         ok!

echo strlen($string); // result: 43

After:

$string = remove_utf8_whitespace($string);

echo $string;

thisisatestandanothertestok!

echo strlen($string); // result: 28

PCRE Argument Listing

Source: https://www.rexegg.com/regex-quickstart.html

Character   Legend  Example Sample Match
\t  Tab T\t\w{2}    T     ab
\r  Carriage return character   see below   
\n  Line feed character see below   
\r\n    Line separator on Windows   AB\r\nCD    AB
    CD
\N  Perl, PCRE (C, PHP, R…): one character that is not a line break \N+ ABC
\h  Perl, PCRE (C, PHP, R…), Java: one horizontal whitespace character: tab or Unicode space separator      
\H  One character that is not a horizontal whitespace       
\v  .NET, JavaScript, Python, Ruby: vertical tab        
\v  Perl, PCRE (C, PHP, R…), Java: one vertical whitespace character: line feed, carriage return, vertical tab, form feed, paragraph or line separator      
\V  Perl, PCRE (C, PHP, R…), Java: any character that is not a vertical whitespace      
\R  Perl, PCRE (C, PHP, R…), Java: one line break (carriage return + line feed pair, and all the characters matched by \v)      

If you want to remove all whitespaces everywhere from $tags why not just:

str_replace(' ', '', $tags);

If you want to remove new lines and such that would require a bit more...


You can use trim function from php to trim both sides (left and right)

 trim($yourinputdata," ");

Or

trim($yourinputdata);

You can also use

ltrim() - Removes whitespace or other predefined characters from the left side of a string
rtrim() - Removes whitespace or other predefined characters from the right side of a string

System: PHP 4,5,7
Docs: http://php.net/manual/en/function.trim.php


A simple way to remove spaces from the whole string is to use the explode function and print the whole string using a for loop.

 $text = $_POST['string'];
            $a=explode(" ", $text);
            $count=count($a);
            for($i=0;$i<$count; $i++){

                echo $a[$i];
            }

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

To strip any whitespace, you can use a regular expression

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

See also this answer for something which can handle whitespace in UTF-8 strings.


There are some special types of whitespace in the form of tags. You need to use

$str=strip_tags($str);

to remove redundant tags, error tags, to get to a normal string first.

And use

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

It's work for me.


This is an old post but the shortest answer is not listed here so I am adding it now

strtr($str,[' '=>'']);

Another common way to "skin this cat" would be to use explode and implode like this

implode('',explode(' ', $str));


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

I believe preg_replace would be looking for something like [:space:]


You can do it by using ereg_replace

 $str = 'This Is New Method Ever';
 $newstr = ereg_replace([[:space:]])+', '',  trim($str)):
 echo $newstr
 // Result - ThisIsNewMethodEver

you also use preg_replace_callback function . and this function is identical to its sibling preg_replace except for it can take a callback function which gives you more control on how you manipulate your output.

$str = "this is a   string";

echo preg_replace_callback(
        '/\s+/',
        function ($matches) {
            return "";
        },
        $str
      );

Is old post but can be done like this:

if(!function_exists('strim')) :
function strim($str,$charlist=" ",$option=0){
    $return='';
    if(is_string($str))
    {
        // Translate HTML entities
        $return = str_replace("&nbsp;"," ",$str);
        $return = strtr($return, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
        // Choose trim option
        switch($option)
        {
            // Strip whitespace (and other characters) from the begin and end of string
            default:
            case 0:
                $return = trim($return,$charlist);
            break;
            // Strip whitespace (and other characters) from the begin of string 
            case 1:
                $return = ltrim($return,$charlist);
            break;
            // Strip whitespace (and other characters) from the end of string 
            case 2:
                $return = rtrim($return,$charlist);
            break;

        }
    }
    return $return;
}
endif;

Standard trim() functions can be a problematic when come HTML entities. That's why i wrote "Super Trim" function what is used to handle with this problem and also you can choose is trimming from the begin, end or booth side of string.


Sometimes you would need to delete consecutive white spaces. You can do it like this:

$str = "My   name    is";
$str = preg_replace('/\s\s+/', ' ', $str);

Output:

My name is

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to whitespace

How to create string with multiple spaces in JavaScript git: fatal: I don't handle protocol '??http' Show whitespace characters in Visual Studio Code What is the symbol for whitespace in C? How to print variables without spaces between values Trim whitespace from a String How do I escape spaces in path for scp copy in Linux? Avoid line break between html elements Remove "whitespace" between div element How to remove all white spaces in java