C
C
Chvalov2015-11-09 01:48:06
Yii
Chvalov, 2015-11-09 01:48:06

How to select only even numbers from a string?

There is a number for example 1532479418730154, how can I choose only even numbers from it?
So that at the output I get the following string: 244804

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Andrey Mokhov, 2015-11-09
@Chvalov

$out = preg_replace('/[13579]/', '', '1532479418730154');

Y
yakalashnikov, 2015-11-09
@yakalashnikov

How to understand where there are single-digit, double-digit, three-digit, etc. numbers?

A
Andrew, 2015-11-09
@R0dger

Well, if we consider that each digit is a separate number.

$txt = '1532479418730154';
$arr = str_split($txt);
$mod = array_reduce($arr, function($array, $item) {
            $item%2==0?$array[] = $item: null;
            return $array;
        }, []);
echo implode($mod);

I
Immortal_pony, 2015-11-09
@Immortal_pony

function cutEvenNumbers($string) {
    $result = "";

    for($i=0; $i<strlen($string); $i++) {
        $symbol = (int)$string[$i];

        if ($symbol%2 == 0) {
            $result .= $symbol;
        }
    }
  
    return $result;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question