【问题标题】:How to explode a string but not within quotes in php?如何在php中爆炸字符串但不在引号内?
【发布时间】:2021-05-15 16:45:51
【问题描述】:

我有这个字符串:

$sc = '[csvtohtml_create include_rows="1-10" 
debug_mode="no" source_type="guess" path="largecsv" 
source_files="FL_insurance_sample - Kopia.csv2"  csv_delimiter="," ]'

我试图弄清楚如何用空格分隔值。这本身不是问题,但如果空格在引号内,我不希望它被分开


仔细查看下面的source_files。 (我希望数组中的项目为"FL_insurance_sample - Kopia.csv2"

与:

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

我得到了这个结果:

array (size=11)
  0 => string '[csvtohtml_create' (length=17)
  1 => string 'include_rows="1-10"' (length=19)
  2 => string 'debug_mode="no"' (length=15)
  3 => string 'source_type="guess"' (length=19)
  4 => string 'path="largecsv"' (length=15)
  5 => string 'source_files="FL_insurance_sample' (length=33)
  6 => string '-' (length=1)
  7 => string 'Kopia.csv2"' (length=11)
  8 => string '' (length=0)
  9 => string 'csv_delimiter=","' (length=17)
  10 => string ']' (length=1)

我想要的结果是:

array (size=11)
  0 => string '[csvtohtml_create' (length=17)
  1 => string 'include_rows="1-10"' (length=19)
  2 => string 'debug_mode="no"' (length=15)
  3 => string 'source_type="guess"' (length=19)
  4 => string 'path="largecsv"' (length=15)
  5 => string 'source_files="FL_insurance_sample - Kopia.csv2"' (length=42)
  7 => string 'csv_delimiter=","' (length=17)
  8 => string ']' (length=1)

我一直在寻找相同的问题,但我不确定答案是否就是我正在寻找的答案。请让我朝着正确的方向前进。 preg_split 是我需要的吗?

【问题讨论】:

    标签: php arrays string explode


    【解决方案1】:

    不使用explode,一种选择是使用preg_split

    (请注意,在您想要的结果中,数组的大小应为 array(8) 并且您跳过了一个键 nr 6)

    模式匹配

    • "[^"]+" 使用否定字符类匹配 "..."
    • (*SKIP)(*F) 当前匹配的内容不应成为结果的一部分
    • |或者
    • \h+ 匹配 1 个或多个水平空白字符

    例子

    $sc = '[csvtohtml_create include_rows="1-10" debug_mode="no" source_type="guess" path="largecsv" source_files="FL_insurance_sample - Kopia.csv2"  csv_delimiter="," ]';
    
    var_dump(preg_split('/"[^"]+"(*SKIP)(*F)|\h+/', $sc));
    

    输出

    array(8) {
      [0]=>
      string(17) "[csvtohtml_create"
      [1]=>
      string(19) "include_rows="1-10""
      [2]=>
      string(15) "debug_mode="no""
      [3]=>
      string(19) "source_type="guess""
      [4]=>
      string(15) "path="largecsv""
      [5]=>
      string(47) "source_files="FL_insurance_sample - Kopia.csv2""
      [6]=>
      string(17) "csv_delimiter=",""
      [7]=>
      string(1) "]"
    }
    

    【讨论】:

    • 谢谢!你能描述一下正则表达式的实际作用吗? :-)
    • @bestprogrammerintheworld 当然,1 分钟
    • 非常感谢。你是世界上最好的程序员:-)
    猜你喜欢
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 2011-12-10
    • 2019-03-22
    • 1970-01-01
    • 2011-09-12
    相关资源
    最近更新 更多