[英]Extract numeric value from an alphanumeric string without using any predefined function
I have a variable 我有一个变量
$string = "(123) 011 - 34343678";
and I want 12301134343678 as an output in integer data type. 我希望12301134343678作为整数数据类型的输出。 How can I do this without using any predefined function in PHP or in any other programming language. 如果不使用PHP或任何其他编程语言中的任何预定义函数,我该怎么做。
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
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 输出: 1555011
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.