我将此代码设为preg_replace youtube代码,但我遇到了问题,这是我的代码
// replace video Youtube to thumbnail
$string = array('http://youtube.com/watch?v=slBEtqC_JsI', 'https://youtu.be/bOxza0rLv1o');
//fix the '/' in the end of url
$string = trim($string, '/');
$search = array();
$search[0] = '~(?:https://(?:www\.)?youtube\.com\/watch\?v=)?([a-zA-Z0-9_\-+?:]+)~';
$search[1] = '~(?:https://(?:www\.)?youtu\.be\/)?([a-zA-Z0-9_\-+?:]+)~';
$replace = array();
$replace[1] = 'https://i.ytimg.com/vi/$1/hqdefault.jpg';
$replace[0] = 'https://i.ytimg.com/vi/$1/hqdefault.jpg';
$soc_youtube = preg_replace($search,$replace,$string);
代码不会改变字符串,输出将是
https://i.ytimg.com/vi/https:/hqdefault.jpg//https://i.ytimg.com/vi/i/hqdefault.jpg.https://i.ytimg.com/vi/ytimg/hqdefault.jpg.https://i.ytimg.com/vi/com/hqdefault.jpg/https://i.ytimg.com/vi/vi/hqdefault.jpg/https://i.ytimg.com/vi/https:/hqdefault.jpg/https://i.ytimg.com/vi/hqdefault/hqdefault.jpg.https://i.ytimg.com/vi/jpg/hqdefault.jpg//https://i.ytimg.com/vi/https:/hqdefault.jpg//https://i.ytimg.com/vi/i/hqdefault.jpg.https://i.ytimg.com/vi/ytimg/hqdefault.jpg.https://i.ytimg.com/vi/com/hqdefault.jpg/https://i.ytimg.com/vi/vi/hqdefault.jpg/https://i.ytimg.com/vi/youtu/hqdefault.jpg/https://i.ytimg.com/vi/hqdefault/hqdefault.jpg.https://i.ytimg.com/vi/jpg/hqdefault.jpg.https://i.ytimg.com/vi/https:/hqdefault.jpg//https://i.ytimg.com/vi/i/hqdefault.jpg.https://i.ytimg.com/vi/ytimg/hqdefault.jpg.https://i.ytimg.com/vi/com/hqdefault.jpg/https://i.ytimg.com/vi/vi/hqdefault.jpg/https://i.ytimg.com/vi/be/hqdefault.jpg/https://i.ytimg.com/vi/hqdefault/hqdefault.jpg.https://i.ytimg.com/vi/jpg/hqdefault.jpg/https://i.ytimg.com/vi/https:/hqdefault.jpg//https://i.ytimg.com/vi/i/hqdefault.jpg.https://i.ytimg.com/vi/ytimg/hqdefault.jpg.https://i.ytimg.com/vi/com/hqdefault.jpg/https://i.ytimg.com/vi/vi/hqdefault.jpg/https://i.ytimg.com/vi/bOxza0rLv1o/hqdefault.jpg/https://i.ytimg.com/vi/hqdefault/hqdefault.jpg.https://i.ytimg.com/vi/jpg/hqdefault.jpg);
任何人都可以帮助我吗? 谢谢你的帮助
答案 0 :(得分:1)
您可以使用
'~(?:https?://(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/))?([a-zA-Z0-9_\-+?:]+)/?~'
请参阅regex demo。模式细节:
(?:
- 第一个轮换组的开始:
https?://(?:www\.)?youtu
- https://
或https://
,然后是可选的www.
子字符串,然后是youtu
子字符串(?:
- 第二轮组的开始:
be\.com/watch\?v=
- be.com/watch?v=
substring |
- 或\.be/
- .be/
substring )
- 第二轮交替小组结束)?
- 1或0次([a-zA-Z0-9_\-+?:]+)
- 第1组:一个或多个字词,-
,+
,?
或:
字符/?
- 可选的/
请参阅PHP demo online:
$string = array('http://youtube.com/watch?v=slBEtqC_JsI', 'https://youtu.be/bOxza0rLv1o', 'http://youtube.com/watch?v=slBEtqC_JSJ/');
$search = '~(?:https?://(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/))?([a-zA-Z0-9_+?:-]+)/?~';
$replace = 'https://i.ytimg.com/vi/$1/hqdefault.jpg';
$soc_youtube = preg_replace($search,$replace,$string);
print_r($soc_youtube);
输出:
Array
(
[0] => https://i.ytimg.com/vi/slBEtqC_JsI/hqdefault.jpg
[1] => https://i.ytimg.com/vi/bOxza0rLv1o/hqdefault.jpg
[2] => https://i.ytimg.com/vi/slBEtqC_JSJ/hqdefault.jpg
)