php - 用空格和引号将字符串拆分为数组

时间:2016-01-13 05:47:03

标签: php arrays regex

让我说我有以下字符串

$string1 = 'hello world my name is'

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

将其与string1:

一起使用
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中的第一个参数?还有其他任何简单的解感谢

1 个答案:

答案 0 :(得分: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