phpstringreplacephone-numbersanitization

Sanitize formatted phone number string by removing two known substrings


I have a value saved in array $phone and want to remove "Tel. " and " - ". The orignal value of $phone is "Tel. +47 - 87654321" and I want it to be "+4787654321".

So far I have made this code:

$phone = Tel. +47 - 87654321;

echo "<br />"
. str_replace("Tel. ","",($phone->textContent)
. str_replace(" - ","",$phone->textContent));

This results:

+47 - 87654321+4787654321

How can I avoid printing (echo) the first part of this code? Is there a better way to do this?


Solution

  • Don't concatenate results from both functions because they're returning whole string after changes.

    Instead change it in next calls

     $string = str_replace("Tel. ", "", $phone->textContent);
     $string = str_replace(" - ", "", $string);
    

    or pass array of items to str_replace().

     $string = str_replace(array("Tel. ", " - "), "", $phone->textContent);