我有這個字串:
$shortcode = '[csvtohtml_create include_rows="1-10"
debug_mode="no" source_type="guess" path="largecsv"
source_files="test?output=csv" csv_delimiter="," ]'
我想檢索屬性及其值,甚至是引號內的等號或空格。
這個問題基于這個問題:如何在 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 );
我得到這個結果: (source_files without output=csv)
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);
uj5u.com熱心網友回復:
你在正確的軌道上爆炸等號。此實作確實array_shift獲取密鑰,然后implodes將陣列的其余部分放在一起。
<?php
$sc = '[csvtohtml_create include_rows="1-10"
debug_mode="no" source_type="guess" path="largecsv"
source_files="test?output=csv" csv_delimiter="," ]';
$args = array_filter(array_map('trim', preg_split('/"[^"] "(*SKIP)(*F)|\h /', $sc)));
array_shift($args); // remove [csvtohtml
array_pop($args); // remove ]
$output = [];
foreach ($args as $arg) {
$explode = explode('=', $arg);
$key = array_shift($explode);
$value = str_replace('"', '', implode('=', $explode)); // remove str_replace if you want to keep the extra set of quotes
$output[$key] = $value;
}
print_r($output);
結果是
Array
(
[include_rows] => 1-10
[debug_mode] => no
[source_type] => guess
[path] => largecsv
[source_files] => test?output=csv
[csv_delimiter] => ,
)
uj5u.com熱心網友回復:
可能更容易獲得比賽。然后你可以做任何事情。我把它變成一個查詢字串并決議成一個陣列:
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] => ","
)
uj5u.com熱心網友回復:
您可以使用匹配屬性名稱及其值
([^\s=] )=(?|"([^"]*)"|(\S ))
請參閱正則運算式演示。詳情:
([^\s=] )- 第 1 組:除空格和=字符之外的一個或多個字符=- 一個=標志(?|"([^"]*)"|(\S ))- 分支重置組:"([^"]*)"-",然后是除"捕獲到 Group 1之外的任何零個或多個字符,然后是"|- 或者(\S )- 第 2 組:任何一個或多個非空白字符
請參閱PHP 演示:
$sc = '[csvtohtml_create include_rows="1-10"
debug_mode="no" source_type="guess" path="largecsv"
source_files="test?output=csv" csv_delimiter="," ]';
if (preg_match_all('~([^\s=] )=(?|"([^"]*)"|(\S ))~', $sc, $ms)) {
print_r(array_combine($ms[1],$ms[2]));
}
輸出:
Array
(
[include_rows] => 1-10
[debug_mode] => no
[source_type] => guess
[path] => largecsv
[source_files] => test?output=csv
[csv_delimiter] => ,
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/333181.html
