修剪空格

3

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

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

请注意,测试后面但结束引号前有空格。我如何摆脱这个空格?

我尝试使用rtrim,但它只适用于字符串末尾的字符,显然这种情况不是在末尾。

有任何提示吗?谢谢


引号总是在字符串的开头和结尾吗? - Zenshai
是的,到目前为止所有时间都在开头和结尾。 - Mike
6个回答

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"

这个函数可以处理没有引号、只有一个引号在开头或结尾,以及完全被引号包裹的字符串。如果你决定将 " ' " 视为分隔符,你可以将其作为参数传递。


3

这里还有另一种方法,只匹配字符串结尾处的空格序列和引号...

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

1

如果你的整个字符串被引号包围,可以使用之前的答案。但是,如果你的字符串包含引用的字符串,你可以使用正则表达式在引号内进行修剪:

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

1

你可以先移除引号,再去掉空格,最后再加上引号。


1

PHP有一些内置函数可以实现这个功能。看这里。


0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接