How to output only numbers from a PHP string?

Suppose I have this line:

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

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

How can I do it?

Example 2:

 $string = "12,456"; 

It is required:

 $num = 12456; 

Thanks!

+8
string php numbers
source share
4 answers

the correct option would be:

 $string = "Hello! 123 How Are You? 456"; $int = intval(preg_replace('/[^0-9]+/', '', $string), 10); 
+25
source share

You can use this method to select only the number present in the text.

 function returnDecimal($text) { $tmp = ""; for($text as $key => $val) { if($val >= 0 && $val <= 9){ $tmp .= $val } } return $tmp; } 
+4
source share

Use this regular expression !\d!

 <?php $string = "Hello! 123 How Are You? 456"; preg_match_all('!\d!', $string, $matches); echo (int)implode('',$matches[0]); 

enter image description here

+1
source share

You can use below:

 $array = []; preg_match_all('/-?\d+(?:\.\d+)?+/', $string, $array); 

Where $ string is the entered string, and $ array is where each number (not a number!, Including negative values!) Is loaded and available for various additional operations.

0
source share

All Articles