【发布时间】:2017-09-20 15:16:42
【问题描述】:
我想在字符串中获取 youtube 链接 例子
“你好,你怎么查到的https://www.youtube.com/watch?v=r_p8ZXIRFJI”;
然后我得到链接
获得链接后,我想从字符串中删除该链接
适用于所有 youtube 网址
【问题讨论】:
我想在字符串中获取 youtube 链接 例子
“你好,你怎么查到的https://www.youtube.com/watch?v=r_p8ZXIRFJI”;
然后我得到链接
获得链接后,我想从字符串中删除该链接
适用于所有 youtube 网址
【问题讨论】:
使用@aampudia 回答,您可以从Extract URL's from a string using PHP 获取网址并进行解析,
<?php
$pattern='#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#';
$str="hi how are you check it https://www.youtube.com/watch?v=r_p8ZXIRFJI";
preg_match_all($pattern, $str, $match);
// if there are multiple urls then use loop here
print_r($match[0]);
echo '<br/>';
// otherwise just use
echo isset($match[0][0]) ? $match[0][0] : 'No url found';
// and to replace string use
echo '<br/>';
echo strpos($match[0][0],'.youtube.') ? str_replace($match[0][0],'',$str) : 'No youtube url'; // let $match[0][0] is defined and not null
?>
【讨论】:
这里我们使用 regular expression 从字符串中提取 youtube 链接。
正则表达式: (?:https?:\/\/)(?:www\.)?(?:youtube|youtu)\.(?:be|com)\/[^\s]+
注意: Youtube 链接也可以是这种格式https://youtu.be/_3tVL-ZAc4k
示例字符串: 您好,您如何检查它https://www.youtube.com/watch?v=r_p8ZXIRFJI youtube 链接可以是这种类型https://youtu.be/_3tVL-ZAc4k
<?php
$string="hi how are you check it https://www.youtube.com/watch?v=r_p8ZXIRFJI youtube link can be of this type https://youtu.be/_3tVL-ZAc4k";
preg_match_all("/(?:https?:\/\/)(?:www\.)?(?:youtube|youtu)\.(?:be|com)\/[^\s]+/", $string,$matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => https://www.youtube.com/watch?v=r_p8ZXIRFJI
[1] => https://youtu.be/_3tVL-ZAc4k
)
)
【讨论】: