3

so I need to extract the ticket number "Ticket#999999" from a string.. how do i do this using regex.

my current regex is working if I have more than one number in the Ticket#9999.. but if I only have Ticket#9 it's not working please help.

current regex.

 preg_match_all('/(Ticket#[0-9])\w\d+/i',$data,$matches);

thank you.

chris85
  • 23,846
  • 7
  • 34
  • 51
Rabb-bit
  • 805
  • 12
  • 24
  • It is possible that a better / more efficient answer can be provided, but we won't know until you provide the full input string. We understand that your input string can be `Ticket#9`, but we don't know what your input string looks like when you have more than one ticket substring to capture. Please edit your question to clarify your question. – mickmackusa May 22 '17 at 20:49

1 Answers1

3

In your pattern [0-9] matches 1 digit, \w matches another digit and \d+ matches 1+ digits, thus requiring 3 digits after #.

Use

preg_match_all('/Ticket#([0-9]+)/i',$data,$matches);

This will match:

  • Ticket# - a literal string Ticket#
  • ([0-9]+) - Group 1 capturing 1 or more digits.

PHP demo:

$data = "Ticket#999999  ticket#9";
preg_match_all('/Ticket#([0-9]+)/i',$data,$matches, PREG_SET_ORDER);
print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => Ticket#999999
            [1] => 999999
        )

    [1] => Array
        (
            [0] => ticket#9
            [1] => 9
        )

)
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563