【发布时间】:2018-02-19 16:26:28
【问题描述】:
我想从文本 youtube url 字符串(如 https://www.youtube.com/watch?time_continue=218&v=0EB7zh_7UE4)和视频 ID(如 0EB7zh_7UE4)中提取,以便我可以根据视频 ID 在字符串后面注入文本。这是我的示例文本:
This is an example page will show up https://www.youtube.com/watch?time_continue=218&v=0EB7zh_7UE4 Bike https://www.youtube.com/watch?v=0EB7zh_7UE4&feature=youtu.be&app=desktop messenger by day, aspiring actor by night, and this is my website. I live in https://youtu.be/1EB7zh_7UE4 Los Angeles, have a great dog named Jack, and I https://www.youtube.com/watch?v=0EB7zh_7UE4&feature=youtu.be like piña coladasdoohickeys https://www.youtube.com/watch?v=4EB7zh_7UE4 you should go to <a href="http://example.com/wp-admin/">your dashboard</a> to delete this page and create new pages for your content. Have fun!
https://www.youtube.com/watch?v=0EB7zh_7UE4
more
https://www.youtube.com/watch?v=2EB7zh_7UE4&feature=youtu.be
That\'s all..
这是我目前得到的正则表达式,但错误如下:
它在链接字符串的结尾(中间)之前添加
(here)字符串。一世 想在你的 Youtube url 链接字符串末尾添加(here)返回多个
here注入
见代码:
function regex($sample_text) {
if (preg_match_all('#(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\-nocookie\.com\/embed\/|youtube\.com\/(?:embed\/|v\/|e\/|\?v=|shared\?ci=|watch\?v=|watch\?.+&v=))([-_A-Za-z0-9]{10}[AEIMQUYcgkosw048])(.*?)\b#s', $sample_text, $matches, PREG_SET_ORDER)) {
print_r($matches);
foreach ($matches as $match) {
$add = ' (here)';
$processed_text = str_replace($match[0], $match[0] . $add, $sample_text);
}
}
return $processed_text;
}
echo regex($sample_test);
我哪里做错了?
注意:问题+示例文本已更新。
【问题讨论】:
-
“它重复 ID 值”是什么意思?预期的输出是什么,你看到的输出是什么?
-
@Syscall 这不是通用代码,而是为 stackoberflow.com 编辑的。我错过了。问题已解决。
-
$processed_text 每次都从 $sample_text 重置,而不是每个值的运行替换。
-
@IMSoP 我想在你的 Youtube url 链接字符串的末尾注入 `(here)`,而不是在中间添加它。
-
@EvilGeniusJamie 是的!那是错误的一部分。这就是我返回多重注射的原因。如此明亮!谢谢。
标签: php regex preg-match preg-match-all