Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to extract numbers from a string

Short answer

preg_match_all() finds every group of digits:

<?php
 
preg_match_all('/\d+/', 'Order 15, items 3, total 4200', $matches);
 
echo implode(', ', $matches[0]);

Output:

15, 3, 4200

Keeping digits only

Remove everything that is not a digit — this is how phone numbers are cleaned:

<?php
 
echo preg_replace('/\D/', '', '+7 (900) 123-45-67');

Output:

79001234567

Fractional numbers

A pattern with an optional fractional part:

<?php
 
preg_match_all('/\d+(?:\.\d+)?/', 'Width 12.5, height 7', $matches);
 
echo implode(', ', $matches[0]);

Output:

12.5, 7

Functions used in this recipe

  • preg_match_all — Finds every match of a regular expression.
  • preg_replace — Replaces everything that matches a regular expression.
  • intval — Converts a value to an integer.

Thanks for reading!

Donate to the site — we work hard for you.