从数组行中获取子字符串Regex?

时间:2016-02-16 13:30:59

标签: php arrays regex

在每一行都有一个包含此类数据的数组:

  

2015 / 2016-0 5 Gruuu 105 Fac Cience Comm 10073 Com Aud 103032 Tech Real TV 4 First Time feb First Quad 6.0 1 Lory Johnson,Nicholas 1334968 47107453A Cory Stein,Hellen Monster Cr。 pie 5 a 3-2 08704 Iguan NewYork HelenMonste.Caldu@ecamp.ex.net eileen@hot.ex.net 617788050 Si 105/968 17/07/2015 0

是否可以获得并保留突出显示的值?

我认为类似于"得到6个数字总是在一起","得到7个数字总是在一起"和"得到逗号之前的两个字符串和逗号之后的字符串以及总是一起放在一起的7个数字之前"

这是我从文件中填充数组的方式,因此具有此类行的数组称为$csvrow

if ($type == 'text/csv'){
    $csvData = file_get_contents($tname);
    $csvrows = explode(PHP_EOL, $csvData);
    $csvarray = array();

    foreach ($csvrows as $csvrow){
    if (strpos($csvrow, '10073') !== false) {
        $csvarray[] = str_getcsv($csvrow);
        echo $csvrow."<br><br>";

    }
}

2 个答案:

答案 0 :(得分:0)

$str = '2015/2016-0 5 Gruuu 105 Fac Cience Comm 10073 Com Aud 103032 Tech Real TV 4 First Time feb First Quad 6.0 1 Lory Johnson, Nicholas 1334968 47107453A Cory Stein, Hellen Monster Cr. pie 5 a 3-2 08704 Iguan NewYork HelenMonste.Caldu@ecamp.ex.net eileen@hot.ex.net 617788050 Si 105 / 968 17/07/2015 0';

获得6个数字:

preg_match('~\d{6}~', $str, $matches);
print_r($matches);

获取“获取逗号之前的两个字符串和逗号之后的字符串以及始终一起使用的7个数字之前”:

preg_match('~([^\s]+\s+[^\s]+)\s*,\s*([^\s]+)\s*(\d{7})~', $str, $matches);
print_r($matches);

输出:

Array
(
    [0] => 103032
)

Array
(
    [0] => Lory Johnson, Nicholas 1334968
    [1] => Lory Johnson
    [2] => Nicholas
    [3] => 1334968
)

答案 1 :(得分:0)

请更准确地说明您的实际结构。根据给出的信息,您可以提出以下代码:

$regex = '~
    (?<number1>\b\d{6}\b)      # match six digits surrounded by word boundaries
    \K                         # throw away anything to the left
    .*?                        # match everything lazily
    (?<name>[a-zA-Z\h,]+)      # match a letter (lower/uppercase), comma 
                               # or horizontal whitespaces
    (?=\b(?P<number2>\d{7})\b) # make sure the match is followed
                               # by seven digits with word boundaries
~x';

$str = 'your_string_here';
preg_match_all($regex, $str, $matches);
print_r($matches);
// e.g. number1
echo $matches["number1"][0]; // 103032

您想要的输出分别在number1namenumber2组中。 请参阅a demo on ideone.com