Suppose we have this text:
... settingsA=9, 4.2 settingsB=3, 1.5, 9, 2, 4, 6 settingsC=8, 3, 2.5, 1 ...
The question is, how can I capture all the numbers that are on a particular line using one step?
One step means:
- single regex pattern.
- single operation (no loops or partitions, etc.)
- all matches are recorded in one array.
Let's say I want to write down all the numbers that are on the line that starts with settingsB= . The end result should look like this:
3 1.5 9 2 4 6
My unsuccessful attempts:
<?php $subject = "settingsA=9, 4.2 settingsB=3, 1.5, 9, 2, 4, 6 settingsC=8, 3, 2.5, 1"; $pattern = '([\d\.]+)(, )?' // FAILED! $pattern = '(?:settingsB=)(?:([\d\.]+)(?:, )?)' // FAILED! $pattern = '(?:settingsB=)(?:([\d\.]+)(?:, )?)+' // FAILED! $pattern = '(?<=^settingsB=|, )([\d+\.]+)' // FAILED! preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER); if ($matches) { print_r($matches); } ?>
UPDATE 1: The @Saleem example uses, unfortunately, several steps instead of a single step. I am not saying that his example is bad (it really works), but I want to know if there is another way to do this and how. Any ideas?
UPDATE 2: The @bobble bubble provided the perfect solution for this task.