【问题标题】:Regex to extract youtube embed url from an iframe in a string [duplicate]正则表达式从字符串中的 iframe 中提取 youtube 嵌入 url [重复]
【发布时间】:2019-02-17 04:37:36
【问题描述】:

您好,到目前为止,已经有很多关于此的问题。但是我已经尝试了很多,但无法在我需要的地方得到它。

我需要一个正则表达式,它可以从包含 iframe 的字符串中提取 youtube 网址。

示例文本:

<p>

</p><p>Garbage text</p><p><iframe width="560" height="315" src="//www.youtube.com/embed/PZlJFGgFTfA" frameborder="0" allowfullscreen=""></iframe></p>

这是我想出的正则表达式:

(\bhttps?:)?\/\/[^,\s()<>]+(?:\([\w\d]+\)|(?:[^,[:punct:]\s]|\/))

Regex101 test

我在一个函数上使用它,它返回一个空数组。有人知道我的功能有什么问题吗?

function extractEmbedYT($str) {
    preg_match('/(\bhttps?:)?\/\/[^,\s()<>]+(?:\([\w\d]+\)|(?:[^,[:punct:]\s]|\/))/', $str, $matches, PREG_OFFSET_CAPTURE, 0);
    return $matches;
}

编辑 1:更改了我的正则表达式中的捕获组,因此它不会捕获最后一个字符

编辑 2:添加了一些 PHP 代码以放入上下文中,因为它在 Regex101 中工作,但在我的脚本中没有。

【问题讨论】:

  • 如果您不需要捕获,为什么要使用捕获组?将 ([^,[:punct:]\s]|\/) 替换为非捕获组 - (?:[^,[:punct:]\s]|\/)
  • 嗯,这在 Regex101 中有效,但不适用于我的函数...我不明白为什么...你能看看这里3v4l.org/fmG1W 吗?我会相应地更新我的问题,如果您可以发布答案,我也会接受它。
  • 在您的代码中,您有 $string 变量,但您将 $str 传递给 extractEmbedYT 函数 - 请参阅 3v4l.org/1OFDf
  • 天啊...哇,谢谢维克托!没发现

标签: php regex youtube


【解决方案1】:

您需要将捕获组转换为非捕获组:

/(\bhttps?:)?\/\/[^,\s()<>]+(?:\(\w+\)|(?:[^,[:punct:]\s]|\/))/s
                                       ^^^

另外,在代码中,您需要将$string 传递给函数,而不是$str

function stripEmptyTags ($result)
{
    $regexps = array (
        '~<(\w+)\b[^\>]*>([\s]|&nbsp;)*</\\1>~',
        '~<\w+\s*/>~',
    );

    do
    {
        $string = $result;
        $result = preg_replace ($regexps, '', $string);
    }
    while ($result != $string);

    return $result;
}


function extractEmbedYT($str) {
    // Find all URLS in $str

    preg_match_all('/(\bhttps?:)?\/\/[^,\s()<>]+(?:\(\w+\)|(?:[^,[:punct:]\s]|\/))/s', $str, $matches);

    // Remove all iframes from $str
    $str = preg_replace('/<iframe.*?<\/iframe>/i','', $str);


    $str = stripEmptyTags($str);
    return [$str, $matches[0]];
}

$string = '<p>

</p><p>UDA Stagiaire</p><p><iframe width="560" height="315" src="//www.youtube.com/embed/PZlJFGgFTfA" frameborder="0" allowfullscreen=""></iframe></p>';

$results = extractEmbedYT($string);

print_r($results);

请参阅online PHP demo

【讨论】:

    猜你喜欢
    • 2016-04-05
    • 1970-01-01
    • 2015-10-30
    • 2011-07-24
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2013-01-19
    • 2012-10-08
    相关资源
    最近更新 更多