Reputation: 1217
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.
Upvotes: 3
Views: 654
Reputation: 1217
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
Upvotes: 0
Reputation: 59681
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
Upvotes: 4