【问题标题】:php - split string by spaces and quotes without spaces into arrayphp - 用空格和引号将字符串拆分为数组
【发布时间】:2016-01-13 05:47:03
【问题描述】:

假设我有以下字符串

$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中的第一个参数?还有其他简单的解决方案吗?谢谢

【问题讨论】:

  • 为什么不能使用 preg_match_all('/hello world/', $string1, $matches);如果你只想要'hello world'

标签: php arrays regex


【解决方案1】:

试试下面的代码:

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多