简体   繁体   English

如何将一串数字转换为数组?

[英]How to convert a string of numbers into an array?

I have a string eg 1398723242 . 我有一个字符串,例如1398723242 I am trying to check this string and get the odd numbers out which in this case is 13973 . 我试图检查这个字符串并得到奇数,在这种情况下是13973

I am facing problem on how to put this string into an array. 我面临着如何将此字符串放入数组的问题。 After putting the string into an array I know that I have to loop through the array, something like this: 将字符串放入数组后,我知道我必须遍历数组,如下所示:

foreach($array as $value){
    if($value % 2 !== 0){
        echo $value;
    }
}

So can any body please help on the first part on "How to put the above string into an array so I can evaluate each digit in the above loop?" 那么任何正文都可以帮助第一部分“如何将上面的字符串放入一个数组,以便我可以评估上面循环中的每个数字?”

This should work for you: 这应该适合你:

Just use str_split() to split your string into an array. 只需使用str_split()将字符串拆分为数组即可。 Then you can use array_filter() to filter the even numbers out. 然后你可以使用array_filter()来过滤偶数。 eg 例如

<?php

    $str = "1398723242";
    $filtered = array_filter(str_split($str), function($v){
        return $v & 1;
    });
    echo implode("", $filtered);

?>

output: 输出:

13973

Array map is your function (mixed with split ) 数组映射是你的功能(与拆分混合)

$array  = array_map('intval', str_split($number));
foreach($array as $value){
    if($value % 2 !== 0){
        echo $value;
    }
}

Use str_split() http://www.php.net/manual/en/function.str-split.php 使用str_split() http://www.php.net/manual/en/function.str-split.php

$string = "1398723242";
$array = str_split($string);
foreach($array as $value){
    if($value % 2 !== 0){
        echo $value;
    }
}

You have to know if the string is an array of chars. 你必须知道字符串是否是一个字符数组。 so you can just iterate it : 所以你可以迭代它:

<?php
$string = "1398723242";
for($i=0; $i < strlen($string); ++$i){
    if($string[$i]=='....'){
       $string[$i] = ''; // Just replace the index like this
    }  
}
?>

if you want string as result, don't convert to array 如果您希望字符串作为结果,请不要转换为数组

$str = "1398723242";
echo preg_replace('/0|2|4|6|8/','', $str); //13973

Or, more faster 或者,更快

echo str_replace(array(0,2,4,6,8),'', $str); //13973
$str    =   '1398723242';

$strlen = strlen($str);// Get length of thr string
$newstr;
for($i=0;$i<$strlen;$i++){ // apply loop to get individual character
    if($str[$i]%2==1){ // check for odd numbers and get into a string
        $newstr .=  $str[$i]; 
    }
}
echo $newstr;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM