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!
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.
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.
Correct variant will be:
$string = "Hello! 123 How Are You? 456";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
                        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;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With