1

我想从特定的 URl 读取一个参数:

喜欢:http ://www.youtube.com/watch?v=MrOiL74P-9E&feature=watch

输出应该是:MrOiL74P-9E

我尝试搜索,发现了这个功能:

function remove_query_part($url, $term)
{
    $query_str = parse_url($url, PHP_URL_QUERY);
    if ($frag = parse_url($url, PHP_URL_FRAGMENT)) {
        $frag = '#' . $frag;
    }
    parse_str($query_str, $query_arr);
    unset($query_arr[$term]);
    $new = '?' . http_build_query($query_arr) . $frag;
    return str_replace(strstr($url, '?'), $new, $url);
}

该函数只删除一个参数并返回其余参数。任何人都可以编辑此函数以仅返回视频 ID 并忽略 URL 中的任何其他内容。

4

3 回答 3

3
$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $args);

print $args['v'];   // <- MrOiL74P-9E

我想你知道如何把它放到一个函数中......

于 2013-05-10T10:39:25.703 回答
2

又快又脏:

$url='http://www.youtube.com/watch?v=MrOiL74P-9E&feature=watch';

function test($url)
{
    $data=parse_url($url);

    if(!isset($data['query']))
    {
        return null;
    }
    else
    {
        $ex=explode('&', $data['query']);

        foreach($ex as $key => $val)
        {
            $param=explode('=', $val);

            if($param[0]=='v')
            {
                return $param[1];
                break;
            }
        }
    }
}

echo test($url);
于 2013-05-10T10:40:11.567 回答
2

Not tested but you could try....

function remove_query_part($url, $term) { 

// get the query part of the string (i.e. after the '?')
$query_str = parse_url($url, PHP_URL_QUERY);
$queryItems = explode('&', $query_str); 

$item = array(); 
$itemArray = array();
foreach ($queryItems as $item) {
    $itemArray = explode('=', $item); 
if($item[0] == $term) {
    return $item[1]; 
}

} 

return false; 
} 
于 2013-05-10T10:50:50.080 回答