Tutorial :Trimming a white space



Question:

In a string that includes quotes, I always get an extra whitespace before the end quote. For instance

"this is a test " (string includes quotes)

Note the whitespace after test but before the end quote. How could I get rid of this space?

I tried rtrim but it just applies for chars at the end of the string, obviously this case is not at the end.

Any clues? Thanks


Solution:1

Here's another way, which only matches a sequence of spaces and a quote at the end of a string...

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


Solution:2

Well, get rid of the quotes, then trim, then put the quotes back.

Let's make a clean function for that :

<?php    function clean_string($string, $sep='"')   {     // check if there is a quote et get rid of them     $str = preg_split('/^'.$sep.'|'.$sep.'$/', $string);       $ret = "";       foreach ($str as $s)        if ($s)          $ret .= trim($s); // triming the right part        else          $ret .= $sep; // putting back the sep if there is any       return $ret;    }    $string = '" this is a test "';  $string1 = '" this is a test ';  $string2 = ' this is a test "';  $string3 = ' this is a test ';  $string4 = ' "this is a test" ';  echo clean_string($string)."\n";  echo clean_string($string1)."\n";  echo clean_string($string2)."\n";  echo clean_string($string3)."\n";  echo clean_string($string4)."\n";    ?>  

Ouputs :

"this is a test"  "this is a test  this is a test"  this is a test  "this is a test"  

This handle strings with no quote, with one quote only at the beginning / end, and fully quoted. If you decide to take " ' " as a separator, you can just pass it as a parameter.


Solution:3

You could remove the quotes, trim, then add the quotes back.


Solution:4

If your whole string is enclosed in quotes, use one of the previous answers. However, if your string contains quoted strings, you could use a regular expression to trim within the quotes:

$string = 'Here is a string: "this is a test "';  preg_replace('/"\s*([^"]+?)\s*"/', '"$1"', $string);  


Solution:5

PHP has a few built in functions that do this. Look here.


Solution:6

The rtrim function accepts a second parameter that will let you specify which characters you'd like it to trim. So, if you add your quote to the defaults, you can trim all the whitespace AND any quotes, and then re-add your end quote

$string = '"This is a test "' . "\n";  $string = rtrim($string," \t\n\r\0\x0B\"") . '"';  echo $string . "\n";  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »