Home » PHP

PHP: How to get integer or decimal from a string?

29 April 2010 2,405 views Popularity: 5% Share/Bookmark

email

Suppose, I have a string with text and number and I only want the number. I don’t want the characters and text of the string.

Here is the way out:-

In this example, you will get only integer. It will omit all characters and text from the string.

$string = 'Nrs 89,994,874.0098';
echo preg_replace("/[^0-9]/", '', $string);
// output: 899948740098

This example prints decimal numbers removing all the characters from the string.

$string = 'Nrs 89,994,874.0098';
echo preg_replace("/[^0-9\.]/", '', $string);
// output: 89994874.0098

Hope this helps.

Related posts:

  1. Random number, string generation in PHP
  2. PHP: Simple and easy way to format URL string
  3. PHP: Parse Unparse String Array
  4. PHP: Generating Multiple Random String
  5. jQuery: How to replace string, div content and image src?
  6. Javascript: How to get current URL without Query string?
  7. Regular Expression check, Validation in PHP
  8. Convert string to datetime and datetime to string in C#
  9. jQuery: Grey out background and preview image as popup
  10. PHP : Read Write Xml with SimpleXML
  • Mian Waqas

    That’s what i was looking for. Thanks for such a nice code snippet.

  • Moe

    You are my hero… LoL
    This help me so much…
    Thank you for this code snippet…