2016-01-13 124 views
1

比方說,我有一個下列字符串PHP - 分割字符串用空格和引號不帶空格到數組

$string1 = 'hello world my name is' 

$string2 = '"hello world" my name is' 

使用這個與字符串1:

preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $string1, $matches); 

我得到一個數組:

echo $matches[0][0]//hello 
echo $matches[0][1] //world 

使用相同的,但爲String2:

preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $string2, $matches); 

我得到一個數組:

echo $matches[0][0] //"hello world" 
echo $matches[0][1] //my 

但如果我的字符串是:

" hello world " my name is 
//^^   ^^(notice the spaces at beginning and end), 

我會得到:

echo $matches[0][0] //" hello world " 

,當我真的想

"hello world" 

如何修改preg_match_all第一個參數?其他簡單的解決方案?感謝

+0

爲什麼不能使用preg_match_all( '/你好世界/',$字符串1,$匹配);如果你只想要 '世界你好' –

回答

2

試試下面的代碼:

$string = '" hello world " my name is'; 
$string = preg_replace('/"\s*(.*?)\s*"/', '"$1"', $string); 
echo ($string); 
echo "<br />"; 
// OUTPUt : "hello world" my name is 

preg_match_all('/"(?:\\.|[^\\"])*"|\S+/', $string, $matches); 
print_r($matches); 
// OUTPUt : Array ([0] => Array ([0] => "hello world" [1] => my [2] => name [3] => is)) 

echo implode(' ', $matches[0]); 
// OUTPUt : "hello world" my name is 
+0

嗨,夥計,謝謝許多。 – user2580401

相關問題