Page 1 of 1

Extract number and periods from string in php

Posted: 28 Oct 2020, 13:59
by Marius
I have a string with numbers and periods. For example '123456...'
I want to separate 123456 and ... and still get the number and the period in php.
I tried using preg_replace():

Code: Select all

$numbers = preg_replace('/[^0-9]/', '', '123456...');
$period = preg_replace('/./', '', '123456...);
With the code above I can extract the numbers but I can't extract the periods. Is there any other way to extract the periods?

Extract number and periods from string in php

Posted: 28 Oct 2020, 16:14
by Admin
It's because the dot (.) in regex is any character, while \. is literal dot.
Try the following code:

Code: Select all

$matches = null;
$input = '123456...';

preg_match('/(?<nums>\d+)(?<periods>\.+)/', $input, $matches);

$numbers = $matches['nums'];
$periods = $matches['periods'];

$nums_only = preg_replace('/[^\d]/', '', $input);