I want to insert all matched patterns into a single array using a regular expression in PHP.
For example, I have following text:
calculated F 1a5 5W13 153w135 1E55 12_5 1.56 1M55
My php code is like this:
$txt="calculated 1a5 5W13 153w135 1E55 12_5 1.56 1M55";
preg_match_all("/calculated F( ([\d\w_\.]+))+/s",$txt,$matches);
print_r($matches);
I need somethings like as:
Array ( [0] =>1a5, [1]=> 5W13, [2]=> 153w135, [3]=> 1E55, [4]=> 12_5, [5]=> 1.56, [6]=> 1M55)
You may use the following regex solution:
$txt="calculated F 15 513 153135 155 125 156 155";
preg_match_all("/(?:\G(?!\A)|calculated(?:\s+F)?)\s*\K[\w.]+/",$txt,$matches);
print_r($matches[0]);
See the regex demo.
Also, see the PHP demo.
Note that it is basically your regex with a custom \G
based boundary added to match consecutive matches after a specific pattern added. Note that your [\d\w_\.]
is the same as [\w.]
as \w
matches what \d
and _
match.
Pattern details:
(?:\G(?!\A)|calculated(?:\s+F)?)
- either the end of the previous match (\G(?!\A)
, \G
by itself matches start of a string or the end of the previous match, thus, (?!\A)
subtracts the start of string position) or calculated
+ 1 or - optionally - more whitespaces + F
(matched with the calculated(?:\s+F)?
branch)\s*
- zero or more whitespaces\K
- match reset operator[\w.]+
- 1 or more digits, letters, _
or .
characters.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With