【问题标题】:How to store 2 characters before particular set of strings in a php array如何在php数组中的特定字符串集之前存储2个字符
【发布时间】:2019-06-20 15:50:29
【问题描述】:

我有一个 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 存储在一个数组中。 请注意,我要创建一个数值数组。

【问题讨论】:

  • 你能解释一下吗?我不明白33,70 的欲望输出如何?不应该是55,70吗?
  • 我只是举个例子。就像“(F)”,“(A)”之前的每两个字符一样。所以输出将是 33,55,70

标签: php arrays string string-matching


【解决方案1】:

这是一个比我更好的答案(@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();

【讨论】:

  • 理论上这种方法是有效的,但是一旦它是 3 或 4 位数字,它就会停止工作。你可以通过先 strpos (A) 然后 strrpos 到前一个空间来解决这个问题。这两个位置之间是数字。但是有了这一切,preg_match 要简单得多。
【解决方案2】:

另一种选择是使用 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

【讨论】:

  • 也许对用户更友好的是输入要查找的内容并使用“键”将其输出为:3v4l.org/vbFSU
  • @Andreas 感谢您的评论,这是一个很好的建议。考虑到可能的重复,我会选择3v4l.org/HPpjV
  • 这也有效。但在我看来,制作关联多维数组会更好,因为您可以轻松找到 B+ 的值。
猜你喜欢
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
  • 2017-04-08
  • 1970-01-01
相关资源
最近更新 更多