skip to Main Content

I did searches and figured this would be an easy find. Though I haven’t found anything related to exactly what I need and similar questions are from people from overseas that have different phone formats with plus signs. A lot of my phone number entries start with a 1 and a space. I did a simple str_replace then I realized if a number has a 1 in the middle followed by a space, then that would mess it up

$string = trim($string);

$string = str_replace('1 ', '', $string); 

That works for phone numbers beginning with

1 800-555-1111

1 222-555-1111

But in the case the phone number is

1 222 551 1111

Then that 551 and space would mess things up. How can it be rewitten so that only the first 1 and the following space is removed and the rest is untouched? Thanks.

EDIT

I forgot to mention that the entries do not always start with a 1 and a space. Sometimes they may be

888-555-1111

888 555 1111

1 888 555 1111

3

Answers


  1. To remove the first 1 and space

    substr($string,2)(without using the trim() method) or substr($string,1)(if you used the trim() method first) will work but are you sure that your number will always start with a 1 and whitespace?

    Do you have any checks or conditions added to make sure that the user input will always start with a 1 and followed by a space?

    If you are sure about that, then the substring solution removes those first two and then returns the rest of the string.

    Login or Signup to reply.
  2. You can use regex to achieve this:-

    $phone_number = '1 800-555-1111'
    echo preg_replace('/^ds+/', '', $phone_number);
    // Will echo 800-555-1111
    
    $phone_number = '1 800 555 1111'
    echo preg_replace('/^ds+/', '', $phone_number);
    // Will echo 800 555 1111
    
    Login or Signup to reply.
  3. if sometimes the number could be 888-555-1111 -, use if :

    $str = "1 978 981 543";
    $str_check = substr($str, 0, 2);
    $need = "1 ";
    
    if($str_check == $need) {
      echo substr($str, 2);
    } else {
      echo $str;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search