php - 在 PHP 中,如何根据带引号的子字符串将字符串分开?

标签 php regex string parsing arguments

在 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/

相关文章:

javascript - 使用 Javascript 替换文本框中的文本(更改大小写)

html - 根据 TextMate 中的属性修改 HTML 语法

regex - 除非使用正则表达式 ',' 在括号内,否则如何按 ',' 拆分字符串?

c - 将 C 字符串传递给函数

php - Laravel:使用 "where not in"数据库表验证表单请求

php - 获取没有相关对象原则的实体

php - 准备带有变量的 PDO sql 语句来调用值

python - 无法匹配正则表达式模式

c++ - Arduino:字符串连接?

php - Doctrine 2 复合键和 DQL 连接