我有这个字符串:
$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/