How to remove character from a String and turn it into integer value with PHP?

Asked

Viewed 179 times

1

I need to convert an entire string and removing the "R$ " from the value.

$valor = $_SESSION['valor'];

echo $valor;

Return the string: R$ 25,00

I need you to take the R$ and return the entire amount: 2500.

How can I do?

3 answers

4


If you are not calling decimals, commas and want to extract only numbers from text, do the following:

$str = $_SESSION['valor'];
preg_match_all('!\d+!', $str, $matches);

echo $matches;

The exit will be 2500.

  • 1

    Thanks @Cypherpotato and David Alves. It worked.

2

You can simply remove the comma and the R$, this way:

$sua_variavel = str_replace ( ',' , '' , $variave_inicial );
$sua_variavel = str_replace ( 'R$' , '' , $sua_variavel );

In the first line will remove the , and in the second the R$

0

Several ways to achieve this result, another one is:

$valor = preg_replace("/[^0-9]+/i","",$valor);

However it is a numeric output, to convert to int, is used:

$valor = (int) preg_replace("/[^0-9]+/i","",$valor);
//ou
$valor = intval(preg_replace("/[^0-9]+/i","",$valor));

Browser other questions tagged

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