PeeHaa
PeeHaa

Reputation: 72662

Get id from string

I have a string which contains a case id.

Example strings:

[Case 123]
lorem[Case 123]ipsum
[Case 123]ipsum

I want to get the id (123) from the string.

I tried (on string [Case 1359] needsmoreinfo):

$pattern = '/[Case (\d+)]/';
preg_match($pattern, $message->subject, $matches, PREG_OFFSET_CAPTURE);

Which resulted in:

o[0][0]: C
    [1]: 1

Not really what I was looking for :)

What should the pattern look like, or is there another flaw somewhere?

Upvotes: 1

Views: 819

Answers (3)

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22162

You need to escape the brackets. I mean doing \[ and \]. You should have:

$pattern = '/\[Case (\d+)\]/';

Upvotes: 1

mario
mario

Reputation: 145482

You only need to escape the opening square bracket:

$pattern = '/\[Case (\d+)]/';

It's otherwise interpreted as regex meta character which introduces a character class.

Upvotes: 1

Jon Gauthier
Jon Gauthier

Reputation: 25582

[ and ] are characters with special meaning in regular expressions. You need to escape them to tell the regex engine to search for literal [ and ] characters:

$pattern = '/\[Case (\d+)\]/';
preg_match($pattern, $message->subject, $matches, PREG_OFFSET_CAPTURE);

See more on what these characters do when unescaped: regular expression character classes.

Upvotes: 4

Related Questions