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.

1
  • 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. Commented May 22, 2017 at 20:49

1 Answer 1

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
        )

)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.