0

[PHP] I want to strip off domain keyword and leave just TLD. How do i achieve it? I tried some string functions with help of Regex Patterns but they only support 1 domain. But you can see i have multiple entries.

Original String:

{
   "example.biz":"Available",
   "example.co":"Available",
   "example.com":"Unavailable",
   "example.mobi":"Available",
   "example.net":"Unavailable",
   "example.org":"Unavailable"
}

Intended Output.

{
   "biz":"Available",
   "co":"Available",
   "com":"Unavailable",
   "mobi":"Available",
   "net":"Unavailable",
   "org":"Unavailable"
}

1 Answer 1

1

You don't need a regex to achieve this. Your string looks like valid JSON. You can parse it to an array using json_decode() (with second parameter set as TRUE to get an associative array) and then remove everything before the . using strstr() and ltrim():

$string = <<<'EOD'
{
   "example.biz":"Available",
   "example.co":"Available",
   "example.com":"Unavailable",
   "example.mobi":"Available",
   "example.net":"Unavailable",
   "example.org":"Unavailable"
}
EOD;

$jsonArr = json_decode($string, TRUE);
$result = array();

foreach ($jsonArr as $domain => $status) {
    $newkey = ltrim(strstr($domain, '.'), '.');
    $result[$newkey] = $status;
}

echo json_encode($result, JSON_PRETTY_PRINT);

Output:

{
    "biz": "Available",
    "co": "Available",
    "com": "Unavailable",
    "mobi": "Available",
    "net": "Unavailable",
    "org": "Unavailable"
}

Online demo

Sign up to request clarification or add additional context in comments.

6 Comments

Of course... .co.uk needs consideration, as do all other TLDs that are locked to the second level. And it'll only get worse come July when .uk opens up at the second level...
if "example." is a known constant surely it's better to just strip that?
@NiettheDarkAbsol: I know it doesn't handle all the corner cases. It's just a nudge in the right direction. The OP should update it with according to his/her requirements. In general, what you said is true :)
@Emissary: I don't think that's the case. Maybe the OP replaced the actual domain names with example.tld?
Hmm... it might be better to assume two-letter domains aren't valid (as they are almost universally restricted to very specific entities) and use a regex based on that. Fewer corner cases, I think.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.