Space trim

In a line containing quotation marks, I always get extra spaces before the final quote. For instance,

"this is a test" (the string contains quotation marks)

Note the spaces after the test, but until the end of the quote. How could I get rid of this space?

I tried rtrim, but it just applies to the characters at the end of the line, obviously this case does not end there.

Any clues? Thanks

+4
source share
6 answers

Here's another way that matches only the sequence of spaces and quotes at the end of the line ...

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

Well, get rid of the quotes, then trim, and then return the quotes.

Make a clean function for this:

 <?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 line descriptor is without a quote, with one quote only at the beginning / end and is fully quoted. If you decide to take "" as a separator, you can simply pass it as a parameter.

+3
source

You can remove quotes, trim, and then add quotes back.

+1
source

If your entire string is enclosed in quotation marks, use one of the previous answers. However, if a string contains strings , you can use a regular expression to trim inside quotes:

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

There are several built-in functions in PHP that do this. Look at here.

+1
source

The rtrim function accepts a second parameter, which allows you to specify which characters you want to trim. So, if you add your quote to the defaults, you can trim all spaces and any quotes, and then add your final quote again

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

Source: https://habr.com/ru/post/1286483/


All Articles