TryHarder
TryHarder

Reputation: 750

cutting string down in PHP

I am dealing with something very simple and yet I found it very long winded to solve.

I have a string that has a webaddress managed by users... so it can be:

Is there an easy way to recognise and cut it to mydomain.com only? That way it would stay unified?

function after ($this, $inthat) {
if (!is_bool(strpos($inthat, $this)))
return substr($inthat, strpos($inthat,$this)+strlen($this));
};
$web_data="";
if(!strpos($data["web"], "http://") {
$web_data=after ("http:\\", $data["concert_web"]);
}
if(!strpos($data["web"], "https://") {
$web_data=after ("https://", $data["concert_web"]);
}
if(!strpos($data["web"], "www") {
$web_data=after ("www", $data["concert_web"]);
}

I gathered that script but it doesn't feel right, is it future-proof? I am eager to learn and thank you in advance any comment.

Upvotes: 0

Views: 73

Answers (2)

kalabro
kalabro

Reputation: 516

I would personally use regex in combination with preg_replace. Something like this:

// Strings for testing the case.
$domains = [
  'foodomain.com',
  'www.foodomain.com',
  'http://foodomain.com',
  'https://www.foodomain.com',
  'https://www.foodomain.www.com',
];


$result_strings = preg_replace(
  [
    '#^https?://#', // First, remove protocol.
    '#^www.#',      // Remove www. from the beginning.
  ],
  '', // Replace by an empty string.
  $domains // You can pass your string here.
);

print_r($result_strings);  // It will output result string for each of the domains from $domains array.

Output:

Array
(
    [0] => foodomain.com
    [1] => foodomain.com
    [2] => foodomain.com
    [3] => foodomain.com
    [4] => foodomain.www.com
)

Upvotes: 2

Florian Lenz
Florian Lenz

Reputation: 11

You could use a combination of parse_url($URL, PHP_URL_HOST) as AbraCadaver mentioned and RegEx (via preg_match()).

<?php

$URL = 'https://www.sub.domain.tld/file.php?okay=true';
preg_match('/([^\.]+\.[^\.]+)$/', parse_url($URL, PHP_URL_HOST), $m);
$DomainOnly = $m[1];

?>

$DomainOnly will be domain.tld. All subdomains will be trimmed off.

Upvotes: 1

Related Questions