2009-06-19 6 views
4

引用符を含む文字列の中には、必ず終了引用符の前に余分な空白文字があります。インスタンス空白の調整

についてテスト後で終了引用符(文字列は引用符を含みます)

注空白 "これはテストです"。どうすればこのスペースを取り除くことができますか?

私はrtrimを試しましたが、文字列の最後に文字列が適用されていますが、このケースは最後ではありません。

手がかりはありますか?ありがとう

+0

は常に文字列の先頭と末尾にあるqoutesですか? – Zenshai

+0

はい、これまでのところ、すべての時間が開始時であり、努力、可読性、テストケースの場合は –

答えて

3

ここだけの最後にスペースと引用符のシーケンスと一致する別の方法は、です文字列...

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

引用符を削除してトリミングしてから引用符を戻すことができます。

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

?> 

Ouputs:

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

なし引用してこのハンドル文字列、完全に1つの始め/終わりにのみ引用符、および引用されて。 "'"をセパレータとして使用する場合は、パラメータとして渡すことができます。

+0

+1となります。 – karim79

1

文字列全体が引用符で囲まれている場合は、前の回答のいずれかを使用します。しかし、あなたの文字列は、あなたが引用符でトリムする正規表現を使用することができ、引用符で囲まれた文字列が含まれている場合:

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

rtrim関数は、トリミングする文字を指定できるようにする2番目のパラメータを受け入れます。だから、あなたがデフォルトにあなたの引用符を追加する場合、あなたはすべての空白や任意の引用符をトリミングすることができ、その後、再度追加するには終了引用符

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

PHPはこれを行う機能で構築されたいくつかを持っています。 Look here.

関連する問題