user3445515
user3445515

Reputation: 13

How can I split/explode a string by last occurrence of a dot?

I have strings similar to the following ones.

  1. 'abc.com'
  2. 'abc.name.com'
  3. 'abc.xyz.name.org'

I want to split the domain name as:

  1. string1=abc string2=com
  2. string1=abc string2=name.com
  3. string1=abc.xyz string2=name.org

So please help me.

Upvotes: 0

Views: 1454

Answers (3)

Whitebird
Whitebird

Reputation: 185

This should do the trick. I tried to make it as verbose as possible. Online test

<?php
function get_last_dot_occurence ($url ) {
    $fullArray = explode('.', $url);
    $newArray = "";
    switch (count($fullArray)) {
        case 0:
        break;

        case 1:
        $newArray = $url;
        break;

        case 2:
        $newArray = array("string1" => $fullArray[0], "string2" => $fullArray[1]);
        break;

        default:
        $string1 = "";
        for ($i=0; $i < count($fullArray)-2; $i++) { 
            $string1 .= $fullArray[$i];
            if($i != count($fullArray)-3)
                $string1 .= '.';
        }
        $string2 = $fullArray[count($fullArray)-2].'.'.$fullArray[count($fullArray)-1];
        $newArray = array("string1" => $string1, "string2" => $string2);
        break;
    }
    return $newArray;
}
print_r(get_last_dot_occurence("abc.com"));
print_r(get_last_dot_occurence("abc.name.com"));
print_r(get_last_dot_occurence("abc.xyz.name.org"));

Upvotes: 0

Federico J.
Federico J.

Reputation: 15912

Use array_pop() function after explode():

$vars = explode('.', $string);

if ( count($vars) == 3 ) {
    $string2 = $vars[1] . '.' . $vars[2];
    $string1 = $vars[0];
}

if ( count($vars) == 2 ) {
    $string2 = $vars[1];
    $string1 = $vars[0];
}

// Or you may use
$vars = explode('.', $string);

if ( count($vars) == 3 ) {
    $string2 = $vars[1] . '.' . $vars[2];
    $string1 = $vars[0];
}

if ( count($vars) == 2 ) {
    $string2 = array_pop($vars);
    $string1 = array_pop($vars);
}

Check pop and explode in php.net

http://php.net/manual/en/function.array-pop.php

http://php.net/manual/en/function.explode.php

Upvotes: 1

hsz
hsz

Reputation: 152284

You can try with:

$inputs = ['abc.com', 'abc.name.com', 'abc.xyz.name.org'];
foreach ($inputs as $input) {
    $parts  = explode('.', $input);
    $right = [array_pop($parts)];

    if (count($parts) > 1) {
      $right[] = array_pop($parts);
    }

    $output = [
      'left'  => implode('.', $parts),
      'right' => implode('.', $right),
    ];

    var_dump($output);
}

Outputs:

array (size=2)
  'left' => string 'abc' (length=3)
  'right' => string 'com' (length=3)
array (size=2)
  'left' => string 'abc' (length=3)
  'right' => string 'com.name' (length=8)
array (size=2)
  'left' => string 'abc.xyz' (length=7)
  'right' => string 'org.name' (length=8)

Upvotes: 1

Related Questions