I'm using PHP and have a variable with several paragraphs of text. In each paragraph, there's at least one 3-digit number. I need to get a list of each 3-digit number. I only want the first 3-digit number found in each paragraph. For example...
$text="this is a test 123 this is a test, blah blah blah
This is the next paragraph 456 and more text 789 and more more more
And another paragragh is here 222 and that's all.";
I want to end up with a list that looks like this
123, 456, 222
CodePudding user response:
Use /^.*?(\d{3})/m
with preg_match_all
and get only the captured groups.
preg_match_all("/^.*?(\d{3})/m", $text, $matches);
print_r($matches[1]); // Array ( [0] => 123 [1] => 456 [2] => 222 )
CodePudding user response:
Another regex on getting only the firstly appeared 3-digit numbers in each line
preg_match_all("/^(?:\D|\s\d{1,2}\s|\s\d{4,}\s)*\s(\d{3})\s.*$/m", $text, $matches);
print_r($matches[1]); // Array ( [0] => 123 [1] => 456 [2] => 222 )
tested string
$text="this is 2255 a test 123 this is a test, blah blah blah
This is the 11 next paragraph 456 and more text 789 and more more more
And another paragragh is here 222 and that's all.";