Generate a string that only contains the numbers of another string in php

3

I made the following function in php that receives a string, and returns a new string containing only the numbers of the received string.

I just can not concatenate each number to this new string. I've tried the following:

function extraiSoNumsDeString($string){
    //Definindo uma String
    $result="";
    for($i=0; $i<strlen($string); $i++){
        $j = substr($string, $i,1);
        if ($j>="0" and $j<="9") $result=.$j;
    }
    //Retorna uma string contendo apenas o número da conta.
    return $result;
}

But the interpreter has a syntax error on this line:

if ($j>="0" and $j<="9") $result=.$j;

saying that I can not use this point to concatenate $ j to $ result.

Does anyone know how I could do this concatenation? I need to return a single string in this function ...

    
asked by anonymous 03.06.2018 / 19:41

2 answers

5

As pointed out in the comment the syntax error is at the point position. The correct use of this assignment operator is .=

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

    for($i=0; $i<strlen($string); $i++){
        $j = substr($string, $i,1);
        if ($j>="0" and $j<="9") {
            $result .= $j;
        }
    }

    return $result;
}

There are better ways to get the same result with a regex:

$conta = '123 123.321-23';

// Casa tudo que não é numero \D e substitui por nada
echo preg_replace('/\D/', '', $conta);

See working .

    
03.06.2018 / 20:06
3

Friend, you can do as follows: This is a PHP function that leaves only numbers in a variable.

function apenasNumeros($str) {
    return preg_replace("/[^0-9]/", "", $str);
}

//$filtrar = apenasNumeros("vamos 45testar45////321");
//echo $filtrar;
    
03.06.2018 / 19:48