Mike
Mike

Reputation:

Trimming a white space

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

Upvotes: 3

Views: 378

Answers (6)

Babak Naffas
Babak Naffas

Reputation: 12561

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

Upvotes: 1

Bite code
Bite code

Reputation: 596623

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.

Upvotes: 3

Alana Storm
Alana Storm

Reputation: 166046

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";

Upvotes: 0

Paul Dixon
Paul Dixon

Reputation: 300825

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);

Upvotes: 3

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94113

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);

Upvotes: 1

Shane Fulmer
Shane Fulmer

Reputation: 7708

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

Upvotes: 1

Related Questions