Best way to replace more than one character in php

1

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

$fone = str_replace("(", "", $_POST["fone"]);
$fone2 = str_replace(")", "", $fone);
$fone3 = str_replace("-", "", $fone2);
    
asked by anonymous 02.02.2018 / 14:19

2 answers

2

With this same function you can do this. The str_replace accepts an array as a parameter, so just do the following:

$fone = str_replace(['(', ')', '-'], '', $_POST['fone']);
    
02.02.2018 / 14:24
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 to the function

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

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

    
02.02.2018 / 14:24