13

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!

mehulmpt
  • 15,861
  • 12
  • 48
  • 88

5 Answers5

38

Correct variant will be:

$string = "Hello! 123 How Are You? 456";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
4

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;
}
Fopa Léon Constantin
  • 11,863
  • 8
  • 48
  • 82
2

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

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
2

You can use the below:

$array = [];

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

Where $string is the entered string and $array is where each number(not digit!,including also negative values!) is loaded and available for different more operations.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
-1
<?php
    $string = "ABC100";
    preg_match_all('!\d+!', $string, $matches);
    $number = $matches[0][0];
    echo $number;
?>

Output: 100

Sreejith N
  • 25
  • 5
  • 1
    This code-only answer provides no new value to this page or Stack Overflow. Please only answer when you have something unique and valuable to add to the page. Worse, it only displays the first of all matches. – mickmackusa Feb 18 '21 at 05:40