在PHP中将电话号码和扩展名与格式不正确的数据分开

I have a bunch of phone number strings. I need to separate the number from the extension. However, the formatting is obviously all over the place. How would you best achieve this in PHP?

555-555-5555 ext 230
555-555-5555 ex 230
555-555-5555 x 230
555-555-5555 ext. 230
555-555-5555 ext230
555-555-5555 x230
555-555-5555 ext # 230`

I tried to use regex but I've not been able to come up with a pattern that matches everything above.

The phone numbers are also not exactly in good shape themselves. Everything from (555)555-555-5555 to 555 555-555-5555. Oh and some records have multiple numbers separated by words like Mobile:, Cell:, or a newline :D . But, that problem is for another question.

Also, extensions are not always 3 numbers. Could be 2-4.

My expected result would be something along the lines of:

$array = [
    'phone' => '555-555-5555',
    'ext' => '123'
];

Given the phone number is not f-ed up as well. You can do it like this:

$array = array (
    '555-555-5555 ext 230',
    '555-555-5555 ex 230',
    '555-555-5555 x 230',
    '555-555-5555 ext. 230',
    '555-555-5555 ext230',
    '555-555-5555 x230',
    '555-555-5555 ext # 230`',
);

$data = array();
foreach ($array as $val)
{
    while (!is_numeric(substr($val,-1))) {
        $val = substr_replace($val ,"", -1);
    }
    $data[] = array( 
            'num' => substr($val, 0, 12), 
            'ext' => substr($val, -3)
        );
}

echo "<pre>"; print_r($data);

try this

<?php
$number = "555-555-5555 ext 230";

preg_match_all('!\d+!', $number, $matches);

for($x=0;$x<count($matches);$x++){

        for($y=0;$y<count($matches[$x]);$y++){
            if($y == (count($matches[$x]) - 1)){
                    echo $matches[$x][$y];
                }else{
                    echo $matches[$x][$y]."-";

                }
        }
}

?>

result 555-555-5555-230 . btw, what is your expected result ?

Update . I don't know if this is best way, but please give a try

<?php
$number = "555-555-5555 x 230";

preg_match_all('!\d+!', $number, $matches);

for($x=0;$x<count($matches);$x++){

        for($y=0;$y<count($matches[$x]);$y++){
            if($y == (count($matches[$x]) - 1)){
                    $result[]= "#".$matches[$x][$y];
                }else{
                    $result[] = $matches[$x][$y];
                }
        }
}

    for($xy=0;$xy<count($result);$xy++){

        if($xy == count($result) - 1 ){
            $data['ext'][] = $result[$xy];
        }else{
            $data['number'][] = $result[$xy];
        }

    }

    $num = implode("-", $data['number']);
    $ext = implode("", str_replace("#","",$data['ext']));

    $final = array("number" => $num, "ext" => $ext);
    echo "<pre>";print_r($final);

?>