Home > Back-end >  extract part of a string before and after characters
extract part of a string before and after characters

Time:12-13

I need to extract a variable based on a portion of a string. the string corresponds to a third level domain name, as in the example below.

$variable1 = "subdomain1.domain24.com"
$variable2 = "subdomain2.newdomain24.com"

I have to extract from the domain (therefore excluding the subdomain) the tld and the number 24. All domains ends with "24.com"

so result must be:

for variable1 : domain for variable2 : newdomain

CodePudding user response:

Regular expressions is one way for this kind of task

  • the domain must follow a dot
  • 24\.com$ is saying match 24.com at the end of the string

https://www.php.net/manual/en/function.preg-match.php

preg_match('/\.(?<domain>[^\.] )24\.com$/', 'subdomain2.newdomain24.com', $matches );

var_dump($matches);

// array(3) {
//   [0]=> string(16) ".newdomain24.com"
//   ["domain"]=> string(9) "newdomain"
//   [1]=> string(9) "newdomain"
// }

CodePudding user response:

Explode your string on . and remove 2 last characters (as it always 24):


$urls = [
    "subdomain1.domain24.com",
    "subdomain2.newdomain24.com",
];

foreach ($urls as $url) {
    $parts = explode('.', $url);
    
    $domain = substr($parts[1], 0, -2);
    
    var_dump($domain);
}

Example

  • Related