Using PHP to find part of a URL

Take this domain:

http://www.?.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html

How can I use PHP to find everything between the first and second slashes regardless of whether it changes or not?

Those. elderly carers

Any helo would be appreciated.

+3
source share
8 answers
//strip the "http://" part. Note: Doesn't work for HTTPS!
$url = substr("http://www.example.com/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html", 7);

// split the URL in parts
$parts = explode("/", $url);

// The second part (offset 1) is the part we look for
if (count($parts) > 1) {
    $segment = $parts[1];
} else {
    throw new Exception("Full URLs please!");
}
+5
source
$url = "http://www.example.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html";
$parts = parse_url($url);
$host = $parts['host'];
$path = $parts['path'];

$items = preg_split('/\//',$path,null,PREG_SPLIT_NO_EMPTY);

$firstPart = $items[0];
+2
source

:

$url = http://www.example.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html
$urlParts = parse_url($url); // An array
$target_string = $urlParts[1] // 'elderly-care-advocacy'

+1

explode('/', $a);

+1

, , url, . , :

$url = 'http://www.?.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html';
$url_parts = parse_url($url);
if (isset($url_parts['path'])) {
    $path_components = explode('/', $ul_parts['path']);
    if (count($path_components) > 1) {
        // All is OK. Path first component is in $path_components[0]
    } else {
        // Throw an error, since there is no directory specified in path
        // Or you could assume, that $path_components[0] is the actual path
    }
} else {
    // Throw an error, since there is no path component was found
}
+1

, Regular Expression .

, : /[^/]+/, /elderly-care-advocacy/ .

( :/www.?. com/)

0
source

Parse_URL is your best bet. It splits the URL string into components that you can selectively request.

This function can be used:

function extract_domain($url){

    if ($url_parts = parse_url($url), $prefix = 'www.', $suffix = '.co.uk') {
        $host = $url_parts['host'];
        $host = str_replace($prefix,'',$host);
        $host = str_replace($suffix,'',$host);
        return $host;
    }
    return false;
}

$host_component = extract_domain($_SERVER['REQUEST_URI']);
0
source

I was also surprised, but it works.

$url='http://www.?.co.uk/elderly-care-advocacy/...'
$result=explode('/',$url)[3];
0
source

Source: https://habr.com/ru/post/1722991/


All Articles