Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

t0berius's avatar

php search string in email text

Dear community,

I've finished my work on a ticket system nearly. After a ticket is created an email is sent to the user. This e-mail includes at the bottom a line saying: ticket_id:XXXXX. Now when a user answeres to this mail a new reply to his ticket should be created. How can I easily use PHP to get just the ticket_number (XXXXX). Here's a sample email:

new ticket was opened. In case of reply to this e-mail a new answer will be added to your ticket.
ticket_id: 123456
somemore text bla bla

I think using a regex would be to overloaded. Keep in mind users may answer to the same email a few times.

0 likes
5 replies
ohffs's avatar

Most ticket systems I've used have had the ticket number in the subject line rather than the body - which is easier to handle. Using a regex is probably the easiest though - just make sure to use an ? in it so it stops at the first match (something like '/(^ticket_id: ([0-9]+$))?/s') although I guess the ticket_id: will be the same throughout the email so might not matter.

t0berius's avatar

@ohffs Hmm ticket number in the subject. Sounds to be a much better idea I think. I can do the verification and check if email matches user e-mail and ticket_id matches users ticket_id. Sounds nice. Thanks a lot! The regex seems to be invalid checking it @regex101?

ohffs's avatar

I was typing the regex while eating a sandwich and listening to someone on the phone - so wouldn't surprise me ;-) Hope using the subject line works out ok :-)

t0berius's avatar

@ohffs

no problem, could you tell me more about the regex? I'm a amateur when it comes to writing regex.

ohffs's avatar

I was trying (and failing! yay fridays!) was a pattern that would look for 'ticket_id: ' followed by one or more digits ([0-9]+) and then the end of a line $ and the ? means 'quit after the shortest match'. Wrapping the sections in () means you can extract the specific bit that matched what you are after. So for instance this would match a subject line like 'Re: T1234: My regex doesn't work' and print just the number in the results :

$result = preg_match('/T([0-9]+):/', $subject, $matches);
if ($result) {
    print $matches[1] . "\n";
}

Please or to participate in this conversation.