2016-07-08 87 views
1

我使用jwplayer替換了youtube視頻的youtube網址。從字符串中提取網址然後href

$str='<a href="https://www.youtube.com/watch?v=6anwsDt8AhA"> sometext</a>https://www.youtube.com/watch?v=6anwsDt8AhAApr 19, 2015 - Uploaded by Go FreelancerThis feature is not available right now. Please try again later. Published on Apr 19, 2015. How to get anchor ...How to get anchor text/href on click using jQuery? - YouTube Video for get text from html content jquery other than anchor 4:54 https://www.youtube.com/watch?v=6anwsDt8AhA Apr 19, 2015 - Uploaded by Go Freelancer This feature is not available right now. Please try again later. Published on Apr 19, 2015. How to get anchor ...'; 


// $disp_question_desc=$content; 
     $disp_question_desc=str_replace("http", " http", $str); 
     //get list of youtube urls 
     preg_match_all('#\b(?:http(?:s)?:\/\/)?(?:www\.)??(?:youtu\.be\/|youtube\.com\/)[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $disp_question_desc, $urls); 
     if(!empty($urls[0])) 
     { 

      foreach($urls[0] as $key=> $youtubeurl) 
      { 
       $div_id=$div_container."_".$key; 
       $youtubeurl=str_replace("/","\/",$youtubeurl); 
       $youtubeurl=str_replace("?","\?",$youtubeurl); 
       $youtube_content= "<div class='youtube-videos-container' srcval='".$youtubeurl."'><div class='youtube-videos ".$div_id."' id='".$div_id."' ></div></div>"; 
       $disp_question_desc= preg_replace("/".$youtubeurl."/", $youtube_content,$disp_question_desc,1); 
       $youtubeurl=str_replace("\\","",$youtubeurl); 

        if (!preg_match("~^(?:f|ht)tps?://~i", $youtubeurl)) { 
        $youtubeurl = "https://" . $youtubeurl; 
        } 


      } 

echo $disp_question_desc; 


     } 

它在正常文本中的youtube url中工作正常。的$我面臨的問題,如果在href標記YouTube網址,也被更換的YouTube視頻,我需要更換隻剩個網址等則href標籤

輸出網址[0]:

Array 
(
    [0] => https://www.youtube.com/watch?v=6anwsDt8AhA 
    [1] => https://www.youtube.com/watch?v=6anwsDt8AhAApr 
    [2] => https://www.youtube.com/watch?v=6anwsDt8AhA 
) 

回答

1

我將在這裏隨心所欲地嘗試糾正你的第一個正則表達式。

您的解決方案

改變你的正則表達式替換下面的一個,只匹配YouTube網址不在html標籤。

(?<!\")((http:\/\/|https:\/\/)(www.)?(youtube\.com|youtu\.be)\/(watch\?v=|\?v=)([a-zA-Z0-9]+))+(?!\")

如果它不工作,回來後,我會進一步檢查你的代碼。

+0

免責聲明:仍然是相當新的正則表達式,如果這是錯誤的,不工作或炸燬了你的電腦,請不要downvotes – 2016-07-08 07:13:23

+0

工作不拍我,我已經變了樣\t \t preg_match_all(」 #((HTTP:\/\/| HTTPS:(<\「?!)。?\/\ /)(WWW)(YouTube的\ .COM | youtu \ .BE)\ /(手錶\ v = | \ ?v =)([a-zA-Z0-9] +))+(?!\「)#',$ disp_question_desc,$ urls);得到相同的結果 –

+0

據我所見,它的工作原理:[https://regex101.com/r/pL7iC4/1](https:regex101.com/r/pL7iC4/1)如果你有意思別的,@Naisapurushotham,請讓我們知道。 –