Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string starts with 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.

like image 504
Ben Avatar asked Oct 25 '25 14:10

Ben


1 Answers

You can still use the foreach, and then return an array with 2 values if there is a match, so you return early from the loop.

Note that you don't need the equals check here because str_starts_with returns a boolean.

if (str_starts_with($telephone_number, $code)) {

Example

$telephone_number = "015169999999";

foreach ($area_codes as $code) {
    if (str_starts_with($telephone_number, $code)) {
        $result = [$code, substr($telephone_number, strlen($code))];
        break;
    }
}

var_export($result ?? null);

Output

array (
  0 => '01516',
  1 => '9999999',
)

See a PHP demo.

I don't know if you can have multiple areacode matches for a single phone number, but if you want the longest to match first, you might sort your array beforehand starting with the longest string.

like image 111
The fourth bird Avatar answered Oct 27 '25 02:10

The fourth bird