PHP 正则表达式多个实例

PHP Regex Multiple Instances

我目前正在导入 CSV 数据,需要将其全部整理好。

较小的示例数据如下。

"Name","Address"
"John Doe","5111 Fury Rd
Santa Cruz"
"Jane Doe","321 Tess St Texas"
"Josh Doe","653 1st St 
Orlando Florida
United States"

如您所见,我们需要在引号外的换行符处进行拆分,因为 str_getcsv 不是多行。

我原来是用这个表达的。

$lines = preg_split('/[\r\n]{1,2}(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/',$data);

但是 preg_split 当字符串中超过 XXXX 个字符时,床就乱七八糟了。

所以目前求助于 preg_match_all,但正则表达式选择器需要解决问题。

preg_match_all('/^(.*?)[\r\n]{1,2}(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/', $data, $matches);

目前只匹配第一个实例。

Array(
    [0] => Array ( [0] => "Name","Address")
    [1] => Array ( [0] => "Name","Address")
)

有任何线索可以获取return数组中的所有数据吗?

这是一种解析它的方法。我已经注释掉了地址中删除新行的部分。如果你想要它,只需删除评论。

$re = '/\"(.*?)\",\"(.*?)\"/s';
$data = '"Name","Address"
"John Doe","5111 Fury Rd
Santa Cruz"
"Jane Doe","321 Tess St Texas"
"Josh Doe","653 1st St
Orlando Florida
United States"';

preg_match_all($re, $data, $matches);

/*
foreach($matches[2] as &$value){
    $value = str_replace(PHP_EOL, " ", $value);
}
*/
var_dump($matches);

https://3v4l.org/7kRDt

foreach 的输出:

array(3) {
  [0]=>
  array(4) {
    [0]=>
    string(16) ""Name","Address""
    [1]=>
    string(36) ""John Doe","5111 Fury Rd
Santa Cruz""
    [2]=>
    string(30) ""Jane Doe","321 Tess St Texas""
    [3]=>
    string(53) ""Josh Doe","653 1st St
Orlando Florida
United States""
  }
  [1]=>
  array(4) {
    [0]=>
    string(4) "Name"
    [1]=>
    string(8) "John Doe"
    [2]=>
    string(8) "Jane Doe"
    [3]=>
    string(8) "Josh Doe"
  }
  [2]=>
  array(4) {
    [0]=>
    string(7) "Address"
    [1]=>
    string(23) "5111 Fury Rd Santa Cruz"
    [2]=>
    string(17) "321 Tess St Texas"
    [3]=>
    &string(40) "653 1st St Orlando Florida United States"
  }
}

如果您需要使用 preg_match_all(),您可以尝试使用此模式来创建一个匹配数组,然后将 str_getcsv() 映射到结果上;例如:

<?php

$csvString = <<<CSV
"Name","Address"
"John Doe","5111 Fury Rd
Santa Cruz"
"Jane Doe","321 Tess St Texas"
"Josh Doe","653 1st St
Orlando Florida
United States
CSV;


preg_match_all('/(.*)(?:\n)/m', $csvString, $csvRows);

$csvData = array_map(function ($csvRow) {
    return str_getcsv($csvRow);
}, $csvRows[1]);

print_r($csvData);

鉴于您的示例输入,这会产生:

Array
(
    [0] => Array
        (
            [0] => Name
            [1] => Address
        )

    [1] => Array
        (
            [0] => John Doe
            [1] => 5111 Fury Rd
        )

    [2] => Array
        (
            [0] => Santa Cruz"
        )

    [3] => Array
        (
            [0] => Jane Doe
            [1] => 321 Tess St Texas
        )

    [4] => Array
        (
            [0] => Josh Doe
            [1] => 653 1st St
        )

    [5] => Array
        (
            [0] => Orlando Florida
        )

)

希望这对您有所帮助:)