phparraysstring

Check if a string contains a substring from an array of substrings and return that substring


I have an array with all German telephone area codes that is 5266 items long and looks like this:

$area_codes = array(
    '015019',
    '015020',
    '01511',
    '01512',
    '01514',
    '01515',
    '01516',
    '01517',
    '015180',
    '015181',
    '015182',
    '015183',
    '015184',
    '015185',
    'and so on'
);

I also have strings of telephone numbers that look like this:

015169999999

That is, the telephone number strings consist only of digits, without spaces, dashes, parentheses or other characters that are often used to visually structure telephone numbers.

I want to split the area code from the subscriber number and assign each to a separate variable. For the example number above, the expected result would be:

echo $area_code;
01516
echo $subscriber_number;
9999999

To identify the area code within the string, I am looping through the array of area codes:

foreach ($area_codes as $area_code) {
    if (str_starts_with($telephone_number, $area_code) == TRUE) {
        echo $area_code;
        $subscriber_number = str_replace($area_code, "", $telephone_number);
        echo $subscriber_number;
        break;
    }
}

How can I return the area code without looping?


Solutions like this require that I know where to split the string, but the area codes have different lengths.


Solution

  • If you want a fast lookup, you need an associative array with the area codes as the keys. For example (assuming area codes have between 4 and 6 digits):

    $area_codes = array(
        '015019',
        '015020',
        '01511',
        '01512',
        '01514',
        '01515',
        '01516',
        '01517',
        '015180',
        '015181',
        '015182',
        '015183',
        '015184',
        '015185',
    );
    
    // Build an associative array
    $area_lookup = [];
    foreach($area_codes as $code)
        $area_lookup[$code] = 1;
    
    function splitNumber(array $area_lookup, string $telephone_number): array
    {
        for($len=4;$len<=6;$len++)
        {
            $prefix = substr($telephone_number, 0, $len);
            if(isset($area_lookup[$prefix]))
                return ['area_code' => $prefix, 'subscriber_number' => substr($telephone_number, $len)];
        }
        throw new Exception('Invalid number');
    }
    
    $res1 = splitNumber($area_lookup, '015169999999');
    $res2 = splitNumber($area_lookup, '015180999999');
    var_dump($res1, $res2);
    

    Output:

    array(2) {
      ["area_code"]=>
      string(5) "01516"
      ["subscriber_number"]=>
      string(7) "9999999"
    }
    array(2) {
      ["area_code"]=>
      string(6) "015180"
      ["subscriber_number"]=>
      string(6) "999999"
    }
    

    (Demo)