Search code examples
phpregexpreg-match-alltext-extractiondelimited

Get all integers which follow certain symbols in a string with multiple delimiters


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. The numbers are not concrete, they can be any quantity of numbers.


Solution

  • 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

    enter image description here

    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:

    [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

    enter image description here