在 PHP 中,如何根据引用的子字符串用空格分隔字符串?我认为一定有一些命令可以像参数一样解析这种类型的字符串,但我不知道那是什么。
示例字符串:
$string = '12345 abcd "hello world" defgh "nice to meet you" 34554';
我通常使用这三种中的一种来分解字符串。但我不认为他们有能力像我建议的那样分解字符串。
$result = str_replace(' ',"\n",$string);
$result = explode(' ',$string);
$result = preg_replace('#\s#',"\n",$string);
结果:
12345
abcd
"hello
world"
defgh
"nice
to
meet
you"
34554
期望的结果:
12345
abcd
hello world
defgh
nice to meet you
34554
更新
我想我对 PHP 处理 URL 查询变量的 parse_str
命令印象深刻,并希望 PHP 有一些东西可以用于这个例子,有点像 getopt
对命令行参数执行此操作。
最佳答案
您可以使用 fgetcsv()/str_getcsv()为此。
<?php
$string = '12345 abcd "hello world" defgh "nice to meet you" 34554';
$row = str_getcsv($string, ' ');
var_dump($row);
打印
array(6) {
[0]=>
string(5) "12345"
[1]=>
string(4) "abcd"
[2]=>
string(11) "hello world"
[3]=>
string(5) "defgh"
[4]=>
string(16) "nice to meet you"
[5]=>
string(5) "34554"
}
关于php - 在 PHP 中,如何根据带引号的子字符串将字符串分开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8081669/