title: Can't remove all newlines from a string - last one still remains
body: <p>I quite never post here, since I always find an answer in other posts... but this time nothing works, I don't know what I'm doing wrong.</p>
  
  <p>I need to var_dump a variable to a string. I found <code>ob_start()</code> and <code>ob_get_clean()</code> in php manual to achieve this.</p>
  
  <p>For text-logfile/debugging needs, I want all \n, \r, multiple spaces and so on to be cleared.</p>
  
  <p>My searches on SO brought me solutions like </p>
  
  <pre><code>$r = preg_replace( '/\s+/', ' ', trim($r));
  //or
  $r = trim(preg_replace( '/\s+/', ' ', $r));
  //I even tried this:
  $r = trim(preg_replace( '/\s+/', ' ', trim($r)));
  </code></pre>
  
  <p>But I can get rid of the last newline character with none of these solutions.</p>
  
  <p>Here the code of the function:</p>
  
  <pre><code>function var_dump_to_string ($v,$style='normal') {
      ob_start();//use buffering to catch direct output from var_dump()
      var_dump($v);
      $r=ob_get_clean();
      if($style=='flat')//just a flat string with no \r\n nor extra whitespaces
          $r = trim(preg_replace( '/\s+/', ' ', trim($r))); 
      return $r;
  }
  </code></pre>
  
  <p>There's still an undesired newline in my textlog. I tried to var_dump the result of this function, there really IS a newline in it...
  What am I missing?</p>
  
  <p><strong>EDIT : the (working) function now looks like this</strong>, thanks to @vks and @anubhava answers:</p>
  
  <pre><code>function var_dump_to_string ($v,$style='normal') {
      $r = var_export($v, true);
      if($style=='flat')  $r = preg_replace('/\s+|\s$/', ' ', $r);
      return $r;
  }
  </code></pre>