开发者

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 could i use PHP to find the everything between the first and second slash regardless of whether it changes or no?

Ie. elderly-care-advocacy

Any helo would be greatly app开发者_如何转开发reciated.


//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!");
}


$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];


off the top of my head:

$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'

Cheers


explode('/', $a);


All you should do, is parse url first, and then explode string and get first part. With some sanity checks that would lok like following:

$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's 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
}


I was surprised too, but this works.

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


I think a Regular Expression should be fine for that.

Try using e.g.: /[^/]+/ that should give you /elderly-care-advocacy/ as the second index of an array in your example.

(The first string is /www.?.com/)


Parse_URL is your best option. It breaks the URL string down into components, which you can selectively query.

This function could 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜