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.
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.
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+/
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.