Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Take Out Only Numbers From A PHP String?

Suppose, I have this string:

$string = "Hello! 123 How Are You? 456";

I want to set variable $int to $int = 123456;

How do I do it?

Example 2:

$string = "12,456";

Required:

$num = 12456;

Thank you!

like image 318
mehulmpt Avatar asked Mar 29 '14 07:03

mehulmpt


People also ask

How do I separate a number from a string?

Approach : The idea is to take a substring from index 0 to any index i (i starting from 1) of the numeric string and convert it to long data type. Add 1 to it and convert the increased number back to string. Check if the next occurring substring is equal to the increased one.

How do you get a specific value from a string in PHP?

Answer: Use the PHP substr() function The PHP substr() function can be used to get the substring i.e. the part of a string from a string. This function takes the start and length parameters to return the portion of string.


2 Answers

Correct variant will be:

$string = "Hello! 123 How Are You? 456";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
like image 100
Iłya Bursov Avatar answered Nov 03 '22 13:11

Iłya Bursov


You can use this method to select only digit present in your text

function returnDecimal($text) {
    $tmp = "";  
    for($text as $key => $val) {
      if($val >= 0 && $val <= 9){
         $tmp .= $val
      }
    }
    return $tmp;
}
like image 39
Fopa Léon Constantin Avatar answered Nov 03 '22 15:11

Fopa Léon Constantin