Best way to replace more than one character in php

Asked

Viewed 41 times

1

I’m using the str_replace of php to leave a phone without the mask. I’m doing it this way, but wanted to know if there is another function that makes it more objective.

$fone = str_replace("(", "", $_POST["fone"]);
$fone2 = str_replace(")", "", $fone);
$fone3 = str_replace("-", "", $fone2);

2 answers

2


With this same function you are using it is possible to do this. The str_replace accepts a array as a parameter, then just do the following:

$fone = str_replace(['(', ')', '-'], '', $_POST['fone']);

2

You can pass an array with all the parameters you want to remove.

$fone = '(01)0000-0000';
$retirar = array("(", ")", "-");
$fone = str_replace($retirar, "", $fone);
echo $fone;

or, pass the array directly into the function

$fone = '(01)0000-0000';
$fone = str_replace(["(", ")", "-"], "", $fone);
echo $fone;

If you want to know more about the function I suggest documentation

Browser other questions tagged

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