【问题标题】:PHP find youtube url to embed _match and _replacePHP 找到嵌入 _match 和 _replace 的 youtube url
【发布时间】:2019-06-17 16:58:36
【问题描述】:

无法弄清楚为什么以下代码不起作用。

它需要文本文件内容(字符串),替换 youtube url(来自字符串),然后将其嵌入到其他字符串,但我没有得到任何响应。

// regex
$yt_pre = "/https?:\/\/(?:www)?\.youtu(?:\.be|be\.com)\/watch(?:\?(.*?)&|\?)v=([a-zA-Z0-9_\-]+)(\S*)/i";

// find
preg_match($yt_pre, $text, $yt_find);
$yt_loc = $yt_find[1];

// embed
$yt_rep = "<div class='youtube'><iframe src='https://www.youtube.com/embed/" . $yt_loc . "' frameborder='0' allowfullscreen class='youtube_iframe'></iframe></div>";

// replace
preg_replace($yt_pre, $yt_rep, $text);

【问题讨论】:

  • “但我没有得到回应”是什么意思? $text的内容是什么?你得到了什么?你期待什么?
  • @Toto $text 文件包含带有一些 html 标记和链接的文本。它用于通过 get_file_content 等填充页面。我正在尝试将文本中的 youtube 链接转换为嵌入代码。当我检查警告或来源时..我从上面的代码中没有得到任何改变。没有警报,没有警告,什么都没有。
  • 向我们展示输入文件的摘录和预期结果。
  • 添加了更清晰的代码

标签: php regex preg-replace preg-match


【解决方案1】:

我的猜测是这个表达式可能适用于 youtube 链接,我假设我们会有一个具有这种模式的 ID (([A-Za-z0-9_-]{11})):

https?:\/\/(?:www\.)?youtu(?:be)?(?:\.com|\.be)\/(?:watch\?v=|embed\/watch\?feature=player_embedded&v=)?([A-Za-z0-9_-]{11})(.+)?

Demo

$re = '/https?:\/\/(?:www\.)?youtu(?:be)?(?:\.com|\.be)\/(?:watch\?v=|embed\/watch\?feature=player_embedded&v=)?([A-Za-z0-9_-]{11})(.+)?/m';
$str = 'http://www.youtube.com/watch?v=iwGFalTRHDA
http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related
http://youtu.be/iwGFalTRHDA
http://youtu.be/n17B_uFF4cA
http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4
http://www.youtube.com/watch?v=t-ZRX8984sc
http://youtu.be/t-ZRX8984sc';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

Ref

【讨论】:

    猜你喜欢
    • 2012-07-24
    • 2018-08-13
    • 2013-03-02
    • 2015-12-03
    • 2016-01-19
    • 1970-01-01
    • 2012-06-23
    • 2019-02-20
    • 1970-01-01
    相关资源
    最近更新 更多