Cyborg
Cyborg

Reputation: 1447

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?

Upvotes: 1

Views: 697

Answers (4)

mickmackusa
mickmackusa

Reputation: 47894

There are several ways to accomplish this task. Because the string has a known length and format, you may implement any of the following.

Codes: (Demo)

  • Remove non-digit, non-plus characters:

    echo preg_replace('/[^\d+]+/', '', $phone);
    
  • Remove the two known, literal strings:

    echo str_replace(['Tel. ', ' - '], '', $phone);
    
  • Remove the two known, literal strings:

    echo strtr($phone, ['Tel. ' => '', ' - ' => '']);
    
  • Parse the static and dynamic segments, then concatenate:

    echo implode(sscanf($phone, 'Tel. %s - %s'));
    
  • Extract substrings by their predictable offsets and length in the formatted string, then concatenate:

    echo substr($phone, 5, 3) . substr($phone, -8);
    

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53525

echo preg_replace ("/^(.*)(?=\\+)(.*)$/", "$2", "Tel. +47 - 87654321" )

will output:

+47 - 87654321

Explanation:
it uses regex in order to divide the string into two groups:

  1. all the characters that come before the + (using lookahead)
  2. anything that comes after the + including the +

and then replace it only with the second group

Upvotes: 0

user1864610
user1864610

Reputation:

Assign your intermediate result to a variable. Try:

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

Upvotes: 0

Elon Than
Elon Than

Reputation: 9765

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);

Upvotes: 3

Related Questions