2017-04-24 77 views

回答

0

這裏我們使用regular expression來從字符串中提取youtube鏈接。

正則表達式:(?:https?:\/\/)(?:www\.)?(?:youtube|youtu)\.(?:be|com)\/[^\s]+

Try Regex demo here

注: Youtube鏈接可能是這種格式也https://youtu.be/_3tVL-ZAc4k

例字符串:你好你怎麼檢查它https://www.youtube.com/watch?v=r_p8ZXIRFJI的YouTube鏈接可以是這種類型https://youtu.be/_3tVL-ZAc4k

Try this code snippet here

<?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 
     ) 

) 
0

使用@aampudia答案,從Extract URL's from a string using PHP你可以得到的URL和解析它像,

<?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 
?> 

PhpFiddle