phpphone-numberstring-parsingspoken-language

How do I convert a hyphenated phone number to words (with 0 as "oh")?


I'm working on a text to speech project, and I don't know how to handle US phone numbers. All phone numbers are in this format: 123-456-7890

I would like it to be converted to this: one two three, four five six, seven eight nine zero.

This is for a news story which will be converted to voice. Currently, text to voice doesn't handle phone numbers very well. For instgance, for the number 123-456-7890, it will convert to voice as one two three four (pause) five six seven (pause) eight nine zero. So, it pauses one number AFTER the area code. If the phone number is typed out, the audio is correct.

The phone number will be incldued in a string that contains the rest of the news story, meaning I just need to replace the numbers of a phone number...in xxx-xxx-xxxx format with words, leaving the rest of the string as is.

How can I achieve this? I'm not very good at understanding regex formats and this that I found online:

/^\([0-9]{3}-[0-9]{3}-[0-9]{4}\$/

doesn't match any valid phone numbers in the text.


Solution

  • After the question requirements were edits, I recommend isolating the strictly-formatted phone number and replacing each digit with its equivalent word. Demo

    $text = 'Call 123-456-7800 between 16:00 and 4:00 for confidential support';
    
    $f = new NumberFormatter('en', NumberFormatter::SPELLOUT);
    echo preg_replace_callback(
             '/\b(\d)(\d)(\d)-(\d)(\d)(\d)-(\d)(\d)(\d)(\d)\b/',
             fn($m) => implode(' ', array_map([$f, 'format'], array_slice($m, 1))),
             $text
         );
    // Call one two three four five six seven eight zero zero between 16:00 and 4:00 for confidential support