Extract numeric value from alphanumeric string without using any predefined function

I have a variable

$string  = "(123) 011 - 34343678";

      

and i want 12301134343678 as output in integer data type. How can I do this without using any predefined function in PHP or any other programming language.

+3


source to share


2 answers


Well, this is not the nicest solution, but something like this might work for you:

Here I am just looping through all the characters and checking if they are all the same when you pass them to an integer and then back to the string. If yes, then this number is different.

<?php

    function own_strlen($str) {
        $count = 0;
        while(@$str[$count] != "")
            $count++;
        return $count;
    }

    function removeNonNumericalCharacters($str) {
        $result = "";

        for($count = 0; $count < own_strlen($str); $count++) {
            $character = $str[$count];
            if((string)(int)$str[$count] === $character)
                $result .= $str[$count];
        }

        return $result;

    }

    $string  = "(123) 011 - 34343678";
    echo removeNonNumericalCharacters($string);

?>

      



output:

12301134343678

      

+4


source


another solution

<?php
$str =  "15as55 - (011)";

$num_array = array();
for($i = 0;$i<=9;$i++)
{
$num_array[]=$i;    
}


for($coun_str = 0 ; isset($str[$coun_str]) && ($str[$coun_str] != "")  ; )
{
$coun_str++;    
}

$strlen = $coun_str - 1;


$outstr = "";
for($j=0;$j<=$strlen;$j++)
{

    foreach($num_array as $val)
    {
        if((string)$val == $str[$j])
        {
            $outstr .= $str[$j]; 


        }
    }




}
echo $outstr
?>

      



output: 1555011

0


source







All Articles