简体   繁体   English

PHP正则表达式和preg_match

[英]PHP regex and preg_match

I have a string that I need to match, which can be in various formats: 我有一个我需要匹配的字符串,可以是各种格式:

5=33
5=14,21
5=34,76,5
5=12,97|4=2
5=35,22|4=31,53,71
5=98,32|7=21,3|8=44,11

I need the numbers that appear between the equal sign (=) and pipe (|) symbol, or to the end of the line. 我需要在等号(=)和管道(|)符号之间出现的数字,或者行的末尾。 So in the last example I need 98 , 32 , 21 , 3 , 44 , 11 but I can't figure this out at all. 因此,在最后一个例子,我需要98322134411 ,但我不知道这一点的。 The numbers are not concrete, they can be any quantity of numbers. 数字不具体,可以是任意数量的数字。

I am just learning regex and preg_match and can't figure it out. 我只是学习正则表达式和preg_match而无法搞清楚。 I have no idea what I am doing. 我不知道我在做什么。

Any help is greatly appreciated. 非常感谢任何帮助。

Try below: 试试以下:

preg_match_all('/(?<==)[^|]*/', $string, $matches);
var_dump($matches);

Description 描述

This expression will: 这个表达式将:

  • match only numbers 只匹配数字
  • requires the numbers to have a comma, vertial pipe, or end of string directly after the number, this prevents the numbers with an equals sign from being included. 要求数字在数字后面直接有逗号,垂直管道或字符串结尾,这样可以防止包含等号的数字。

\\d+(?=[,|\\n\\r]|\\Z) Live Demo \\d+(?=[,|\\n\\r]|\\Z) 现场演示

在此输入图像描述

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  \d+                      digits (0-9) (1 or more times (matching
                           the most amount possible))
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    [,|\n\r]                 any character of: ',', '|', '\n'
                             (newline), '\r' (carriage return)
--------------------------------------------------------------------------------
   |                        OR
--------------------------------------------------------------------------------
    \Z                       before an optional \n, and the end of
                             the string
--------------------------------------------------------------------------------
  )                        end of look-ahead

Examples 例子

Samples 样品

With this expression the string 5=98,32|7=21,3|8=44,11 will return an array of strings: 使用此表达式,字符串5=98,32|7=21,3|8=44,11将返回一个字符串数组:

[0] => 98
[1] => 32
[2] => 21
[3] => 3
[4] => 44
[5] => 11



Or 要么

You could just look for all numbers which are not followed by an equals sign 您可以查找所有未跟随等号的数字

\\d+(?!=|\\d) Live Demo \\d+(?!=|\\d) 现场演示

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM