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

Asked

Viewed 38 times

3

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

I’m just not able to concatenate each number to this new string. I 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;
}

Only the interpreter has syntax error on this line:

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

saying I can’t use this point to concatenate $j to $result.

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

  • 1

    Would not be .= $j instead of = .$j?

2 answers

5


As pointed out in the comment the syntax error is at the point position. The correct use of this allocation 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);

Behold working.

3

Buddy, you can do it like this: 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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.