Alex Ferg
Alex Ferg

Reputation: 871

PHP preg_match to extract a certain number from a string

I have a multi line string like:

$msg = "Fix #1: This is a message
Fix #2
Fix #5";

I've tried a lot of patterns but none worked the way I want it to work.

What I want preg_match to do is to return an array with 1, 2 and 5. The pattern should check for all Fix #NUM and return all the NUM in an array.

Upvotes: 0

Views: 570

Answers (3)

hwnd
hwnd

Reputation: 70722

You can use preg_match_all() and simply match digits alone to return the desired results.

preg_match_all('/\d+/', $msg, $matches);
var_dump($matches[0]);

If the matches need to be preceded by Fix #, you can use the following:

preg_match_all('/Fix\s+#\K\d+/', $msg, $matches);

This matches "Fix" followed by whitespace characters "one or more" times followed by #.

The \K escape sequence resets the starting point of the reported match and any previously consumed characters are no longer included.

Upvotes: 1

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13263

If Fix # has to be in-front of the number then something like this should do it:

/(?<=Fix\s+#)\d+/

Otherwise this is fine:

/\d+/

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

You need to use preg_match_all with this \d+ regex because preg_match would return only a single match. It won't do a global match.

Upvotes: 0

Related Questions