如何存储特定组字符串的前2个字符的PHP数组

问题描述 投票:0回答:2

我有一个PHP字符串文本文件的内容。现在我想以下字符串之前发生的两个字符存储 - "(A)","(B)","(C)","(B+)"例如,如果php变量包含类似 -

33(F) 15352(1) 24 31 55(B+) 15360(1) 6 32 38 70(A) 2 3 4 5 6 7 8 9 10
10
*Passed with Grace Marks
*SID:  Student  ID;                          SchemeID:  The  scheme  
applicable  to  the  student.
Date on which pdf made: 09/10/2018
RTSID: 2018100901520151640002

然后,我想存储33,70在数组中。请注意,我想创建一个数字数组。

php arrays string string-matching
2个回答
1
投票

另一种选择是使用preg_match_all和捕获1+位数捕获组,随后通过匹配一个大写字符接着任选的加\d+(或2个位数恰好\d{2}登录\([A-Z]\+?

然后从得到的数组转换使用array_mapintval的值。

例如:

$re = '/(\d+)\([A-Z]\+?\)/';
$str = '33(F) 15352(1) 24 31 55(B+) 15360(1) 6 32 38 70(A) 2 3 4 5 6 7 8 9 10
10
*Passed with Grace Marks
*SID:  Student  ID;                          SchemeID:  The  scheme  
applicable  to  the  student.
Date on which pdf made: 09/10/2018
RTSID: 2018100901520151640002';

preg_match_all($re, $str, $matches);
var_dump(array_map('intval',$matches[1]));

结果

array(3) {
  [0]=>
  int(33)
  [1]=>
  int(55)
  [2]=>
  int(70)
}

Php demo


2
投票

这是比我更好的答案(由@Andreas):

    $re = '/(\d+)\(([A-Z]\+?)\)/m';
    $str = '33(F) 15352(1) 24 31 55(B+) 56(B+) 15360(1) 6 32 38 70(A) 2 3 4 5 6 7 8 9 10
    10
    *Passed with Grace Marks
    *SID:  Student  ID;                          SchemeID:  The  scheme  
    applicable  to  the  student.
    Date on which pdf made: 09/10/2018
    RTSID: 2018100901520151640002';


    preg_match_all($re, $str, $matches);
    $res = array_map(function($x, $y){
        return [$y, $x];
    },$matches[1], $matches[2]);
    print_r($res);

对于一个单输入,这会工作,它不是最好的:

      function f(){
        $inputs = '33(F) 15352(1) 24 31 55(B+) 15360(1) 6 32 38 70(A) 2 3 4 5 6 7 8 9 10
        10
        *Passed with Grace Marks
        *SID:  Student  ID;                          SchemeID:  The  scheme  
        applicable  to  the  student.
        Date on which pdf made: 09/10/2018
        RTSID: 2018100901520151640002';

        $a=strpos($inputs,'(A)');
        $b=substr($inputs, $a-2,2);
        var_dump($b);
      }

    f();
© www.soinside.com 2019 - 2024. All rights reserved.