php - 从字符串中的引号中提取时如何包含等号和引号?

我有这个字符串:

$shortcode = '[csvtohtml_create include_rows="1-10" 
debug_mode="no" source_type="guess" path="largecsv" 
source_files="test?output=csv"  csv_delimiter="," ]'

我想检索属性及其值,甚至是引号内的等号或空格。

这个问题是基于这个问题:How to explode a string but not within quotes in php?

我有这个代码:

$args = preg_split('/"[^"]+"(*SKIP)(*F)|\h+/', $shortcode);
   
$attrs = [];
foreach( $args as $item )
{
    //Only use those items in array $args with = sign
    if ( strpos( $item , '=' ) !== false )
    {
        $sep = explode( '=', $item );
        $key = $sep[0];
        $value = $sep[1];
        $attrs[$key] = str_replace( '"', '', $value );
    }
}

$args = explode( '=', $sc );

我得到了这样的结果:(没有 output=csv 的 source_files)

Array attrs
      "include_rows" => "1-10"
      "debug_mode" => "no"
      "source_type" => "guess"
      "path" => "largecsv"
      "source_files" => "test.csv?output"
      "csv_delimiter" => ","
 

我想要的结果是:

Array attrs
      "include_rows" => "1-10"
      "debug_mode" => "no"
      "source_type" => "guess"
      "path" => "largecsv"
      "source_files" => "test.csv?output=csv"
      "csv_delimiter" => ","
 

等...

我想我应该在此处的某处输入等号(或者是?=),但正则表达式不是我的强项...

$args = preg_split('/"[^"]+"(*SKIP)(*F)|\h+/', $shortcode);

最佳答案

可能更容易获得比赛。然后你可以做任何事情。我把它变成一个查询字符串并解析成一个数组:

preg_match_all('/[^\s=]+="[^"]*"/', $shortcode, $result);
parse_str(implode('&', $result[0]), $result);

现在 $result 产生:

Array
(
    [include_rows] => "1-10"
    [debug_mode] => "no"
    [source_type] => "guess"
    [path] => "largecsv"
    [source_files] => "test?output=csv"
    [csv_delimiter] => ","
)

要去掉引号然后将其解析为 ini 设置:

$result = parse_ini_string(implode("\n", $result[0]));

产量:

Array
(
    [include_rows] => 1-10
    [debug_mode] => no
    [source_type] => guess
    [path] => largecsv
    [source_files] => test?output=csv
    [csv_delimiter] => ,
)

https://stackoverflow.com/questions/69683430/

相关文章:

r - 如何调整饼图上的 ggrepel 标签?

lua - 波浪号本身在 Lua 中是什么意思?

java - org.gradle.api.internal.tasks.testing.TestS

domain-driven-design - DDD 和 CQRS : use multiple r

haskell - 不同类型的重载/多态函数

javascript - 如何将字符串javascript类型的两位小数相乘

javascript - typescript :如何定义具有许多未知键的对象

r - 使用 dplyr 获取术语列表、分组依据和汇总值

javascript - 如何在 Electron 15 中导入菜单

python - 如何在空字典进入/读取输入列表时将新键添加到空字典?