Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract all matches from a string using single regular expression in PHP?

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)
like image 480
Huseyin Avatar asked Jan 31 '23 02:01

Huseyin


1 Answers

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.
like image 170
Wiktor Stribiżew Avatar answered Feb 03 '23 06:02

Wiktor Stribiżew