【问题标题】:Retrieve value from URL [duplicate]从 URL 中检索值 [重复]
【发布时间】:2020-08-20 03:33:36
【问题描述】:

我正在尝试从 youtube 链接获取视频代码,如下所示:

https://www.youtube.com/watch?v=sLnwdjQQlIw

具体来说,我正在尝试获取“v=”之后的代码。

当链接如下所示时,问题就来了:

https://youtu.be/OKuGTy7D52c

我将如何从该链接获取视频代码?

这是我目前所拥有的:

<?php
    if(isset($_POST["Search"]))
    {
        $url = $_POST["URL"];
        $value = (explode('v=', $url));
        $videoId = $value[1];
    }
?>


<form method="post" class="form-group">
    <input name="url" type="url" class="form-control form-control-lg mb-3" placeholder="https://www.youtube.com/watch?v=9a5TF2U-Fa4" required>
    <button style="background-color:#f2ae06;border:none" name="Search" class="btn btn-primary btn-lg btn-block">Get</button>
</form>

【问题讨论】:

  • 使用str_replace()从字符串中剥离https://youtu.be/?使用parse_url($url, PHP_URL_PATH)获取路径?

标签: php html web


【解决方案1】:

您可以使用此线程中的解决方案:Get characters after last / in url

$pos = strrpos($url, '/');
$id = substr($url, strrpos($url, '/') + 1);

【讨论】:

    【解决方案2】:

    工作流程:

    • 检查给定字符串的格式。
    • 根据格式更改字符串的分割方式。

    更简单的版本:

    使用str_ireplace 并构建一个要从字符串中删除的值数组。您还需要使用 preg_replace 来 REGEX 删除任何查询字符串附加 (QSA),例如时间开始 (?t=23):

    $remove = []; // array
    $remove[] = 'https://www.youtube.com/watch?v=';
    $remove[] = 'https://youtu.be/';
    $remove[] = 'https://www.burning-kittens.com/video='; // etc. etc. 
    
    // replaces each array values in string with nothing. 
    $url = str_ireplace($remove, '', $url); 
    
    // Use Regex to remove any query string appends such as start time etc.
    // https://youtu.be/OKuGTy7D52c?t=23 removes the '?t=23' bit. 
    $url = preg_replace('/(\?.*)/','',$url);
    

    【讨论】:

    • @bigscreenplay 如果这有帮助,您可以使用左上角的向上箭头为答案“投票”,欢呼:-)
    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 2018-07-11
    • 2011-06-21
    • 1970-01-01
    • 2021-11-14
    • 2018-12-31
    • 2013-07-21
    • 1970-01-01
    相关资源
    最近更新 更多