0

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.

2
  • 2
    I've tried a lot of patterns Just show us a few attempts Commented Feb 12, 2015 at 14:48
  • You're probably pretty close with some of your attempts. Show us what you've tried and we can go from there. Commented Feb 12, 2015 at 15:11

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

var_dump($matches[1]) :)
This works pretty good, can you please explain the second pattern? Especially the \K
1

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+/

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.