MyFault
MyFault

Reputation: 427

Get text after brackets

I would like to solve the following problem:

I fetch mails via imap; now I use regexp to get the text between two quare brackets (Ticket-ID).

For example: [Ticket-ID: 84824] Re:Test

preg_match("/\[Ticket-ID: (\S+)\]/", $mail->subject, $matches)

gets 84824 as result - but how can I get "Re:Test" or just "Test" with PHP?

Now I would like to get the pure subject without any ticket-numbers and so on. How can I solve that?

Upvotes: 2

Views: 172

Answers (4)

Andrey Korneyev
Andrey Korneyev

Reputation: 26846

You can use one more capturing group in your regex pattern like this:

preg_match("/\[Ticket-ID: (\S+)\]\s*(.*)/", $mail->subject, $matches)

It will capture "Re:Test" in the second match, so you can retrieve it from $matches[2]

Upvotes: 2

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

Try this regex: \[[^:]+:\s*(\d+)\]

$re = "/\\[[^:]+:\\s*(\\d+)\\]/"; 
$str = "[Ticket-ID: 84824] Re:Test"; 

preg_match($re, $str, $matches);

Demo

Upvotes: 0

champlow007
champlow007

Reputation: 9

$string='[Ticket-ID: 84824] Re:Test';
$bracket_location=strpos($string,'] ');
$subject=substr($string,$bracket_location+2,strlen($string)-$bracket_location+2);

Loop through your matches and your $subject will give you the Re:Test.

Upvotes: 0

Pruthvi Raj
Pruthvi Raj

Reputation: 3036

You can do this:

\[[\s\S]+\][\s]*(.*)

DEMO

Regular expression visualization

Sample Code:

<?php

$str ='[Ticket-ID: 84824] Re:Test';
preg_match('/\[[\s\S]+\][\s]*(.*)/',$str,$matches);
echo $matches[1];

?>

Output :

Re:Test

If you want only Test, use following regex:

\[[\s\S]+\][\s]*Re:(.*)

Upvotes: 1

Related Questions