0

In my support ticket system, replies are sent to the user and the subject includes [Ticket ID: ######] in it.

What could I use to strip the ###### out of there by supplying the entire title?

For example, a function that will turn this:

[Ticket ID: 600238] Forgot password, reset it please :(

into this:

600238

The subjects can start with any characters, though the ticket ID brackets are separated from the subject itself using a space.

Is there an RegEx to do this?

Anonymous
  • 553
  • 5
  • 17
  • 41

2 Answers2

5

You can use preg_match.

if (preg_match("/\[Ticket ID: (\d+)\]/", $input, $matches)) {
    $ticket_id = $matches[1];
}
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • preg_match("\[Ticket ID: (\d+)\]", "RE: [Ticket ID: 5890684] Hello World", $matches) does not work. – Anonymous Sep 05 '12 at 03:13
  • You need to escape the brackets in the regex. My answer includes this, whereas your test code does not. – FThompson Sep 05 '12 at 03:14
  • I do have them escaped, but Stack Overflow removed them in my comment. – Anonymous Sep 05 '12 at 03:15
  • Using Subject: RE: [Ticket ID: 30649722] Hello Ticket ID Found: Items in Array: 0 – Anonymous Sep 05 '12 at 03:17
  • 2
    @Bailey: Have you considered enabling error_reporting when things don't work? – mario Sep 05 '12 at 03:17
  • @mario I wasn't expecting an error, as the script didn't stop and I don't use preg_match, but thanks for that reminder, haha. Error: "Delimiter must not be alphanumeric or backslash" – Anonymous Sep 05 '12 at 03:18
  • Works when I try it in Patterns.app – Ben Sep 05 '12 at 03:20
  • I did after your edit. I still get this error: "Delimiter must not be alphanumeric or backslash" I have exactly what you have in my PHP script. Perhaps PHP is stripping something? – Anonymous Sep 05 '12 at 03:20
  • @Bailey I've edited my answer to account for that (I think; I'm more used to using regex in Java which does not require beginning and ending slash delimeters). – FThompson Sep 05 '12 at 03:22
  • NOW it works. I got the entire "[Ticket ID: ??]" but I will just strip the unnecessary parts out. – Anonymous Sep 05 '12 at 03:22
  • The numeric ID is already in `$matches[1]` - (the whole match is in `$matches[0]`). Use this statement instead: `$ticket_id = $matches[1];` – ridgerunner Sep 05 '12 at 05:56
1

'[' ']' have spacial meaning in regular expression, hence you have to escape them in the regular expression. The regular expression you need is /\[Ticket ID: [\d]{6}\]/

You may want to use [\s]+ in between the words if not sure about number of spaces in between the words.

This Regular expression will give you whole Ticket ID: ###### And again you have to extract the number.

RegExp are very powerful and here you can learn more about RegExp here

Sanuj
  • 1,077
  • 1
  • 11
  • 23