修剪白色空间

时间:2009-06-19 18:21:35

标签: php string

在包含引号的字符串中,我总是在结束引号之前得到一个额外的空格。例如

  

“这是一个测试”(字符串包含引号)

请注意 test 之后但结束引用之前的空格。我怎么能摆脱这个空间?

我试过rtrim,但它只是在字符串末尾应用字符,显然这种情况不在最后。

任何线索?感谢

6 个答案:

答案 0 :(得分:3)

好吧,摆脱引号,然后修剪,然后把引号放回去。

让我们为此做一个干净的功能:

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

?>

输出:

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

这个句柄没有引号,只有一个引用只在开头/结尾,并且完全引用。如果您决定将“'”作为分隔符,则可以将其作为参数传递。

答案 1 :(得分:3)

这是另一种方式,它只匹配一个空格序列和一个字符串 end 的引号...

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

答案 2 :(得分:1)

你可以删除引号,修剪,然后再添加引号。

答案 3 :(得分:1)

如果您的整个字符串都用引号括起来,请使用以前的答案之一。但是,如果您的字符串包含引用的字符串,则可以使用正则表达式在引号内修剪:

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

答案 4 :(得分:1)

PHP有一些内置函数可以做到这一点。 Look here.

答案 5 :(得分:0)

rtrim函数接受第二个参数,让您指定要修剪的字符。因此,如果您将报价添加到默认值,则可以修剪所有空格和任何引号,然后重新添加结束报价

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