【问题标题】:Get substrings from an array rows, Regex? [closed]从数组行中获取子字符串,正则表达式? [关闭]
【发布时间】:2016-02-16 13:30:58
【问题描述】:

在每一行都有一个包含这种数据的数组:

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>";

    }
}

【问题讨论】:

  • Bold values 是什么意思?
  • 抱歉@Tushar 我在完成前按了回车键。 : \
  • 我还是不明白什么是模式,你能解释一下吗
  • 嗯,我想像“获取始终在一起的 6 个数字”、“获取始终在一起的 7 个数字”和“获取逗号之前的两个字符串和逗号之后的字符串和在永远在一起的 7 个数字之前”。解释和编码也不容易。
  • 请将新行放入您的初始输入中,我在这里看不到模式。有什么逻辑吗?

标签: php arrays regex


【解决方案1】:
$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
)

【讨论】:

  • 非常感谢@Mvorisek!这正是我所需要的 :) 只是出于好奇……有没有办法将两个正则表达式放在一个表达式中?
  • preg_match('~\d{6}.*([^\s]+\s+[^\s]+)\s*,\s*([^\s]+)\s*(\d{7})~', $str, $matches); 只需合并正则表达式并在其间添加.* - 这将匹配两个匹配项之间的文本。如果我的回答回答了您的问题,请随时将其标记为答案。
  • 太棒了!!非常感谢您的帮助和时间:)
【解决方案2】:

请更准确地说明您的实际结构。有了给定的信息,你可以想出以下代码:

$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

【讨论】:

    猜你喜欢
    • 2013-07-31
    • 2020-05-13
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2019-05-02
    • 2013-02-09
    • 2014-03-04
    相关资源
    最近更新 更多