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

标签 php regex string

我有这个字符串:

$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] => ,
)

关于php - 从字符串中的引号中提取时如何包含等号和引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69683430/

相关文章:

PHP CURL 错误 - curl : (56) Recv failure: Connection reset by peer

php - 如何从一个类中获取常量,排除所有可能从 parent 那里继承下来的常量?

java - 在 Java 中将字符串拆分为 n 个长度的 block

java - Android 从 Okhttp onResponse 函数中提取字符串

php - 使用 Active Record 模式执行查询 INSERT INTO 时出错

php - 如何上传数据和字符串到服务器[Swift,Php]

javascript - 在 Javascript 中验证电子邮件地址,并与非 ASCII 字符兼容

javascript - 几个正则表达式查询

regex - 是否可以在 WiX 中使用正则表达式验证文本字段?

java - 为什么这些 Java replaceAll 语句不起作用?