Extract number and periods from string in php

Discuss coding issues, and scripts related to PHP and MySQL.
Marius
Posts: 107

Extract number and periods from string in php

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?

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);

Similar Topics