Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract numeric value from an alphanumeric string without using any predefined function

Tags:

java

c++

c

.net

php

I have a variable

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

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

like image 548
Faiyaz Alam Avatar asked Mar 01 '26 01:03

Faiyaz Alam


1 Answers

Well it's not the nicest solution, but something like this could work for you:

Here I simply loop through all characters and check if they are still the same when you cast them to an integer and then back to a string. If yes it is a number otherwise not.

<?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
like image 69
Rizier123 Avatar answered Mar 02 '26 15:03

Rizier123