2014-02-26 150 views
0

我有以下字符串:方括號到YouTube視頻轉換內部視頻ID鏈接

this is a video [youtube erfsdf3445] test 
this is a video [youtube we466f] test 

我試圖建立一個正則表達式與相應的YouTube視頻鏈接代替[youtube erfsdf3445],例如www.youtube.com/watch?v=erfsdf3445。用方括號括起來的文字用於視頻ID。

我該如何做到這一點?

+0

我改寫你的問題有點。如果它與您想要實現的不同,請隨時修改。 –

回答

4

你正在尋找的正則表達式是/\[youtube ([^\]]+)\]/

屍檢

  • \[字面[字符
  • youtube[space]文本字符串 「YouTube」 的(用空格)
  • ([^\]]+)捕獲組(這是$1 ):
    • [^\]]+不是\]任何字符(這是一個文字])匹配1次或更多次(不能爲空)
  • \]字面]字符

Debuggex

Regular expression visualization

在代碼

如果你不想做任何URL編碼,你可以簡單地使用preg_replace

<?php 
    $string = 'this is a video [youtube erfsdf3445] test'; 

    $string = preg_replace('/\[youtube ([^\]]+)\]/', 'http://www.youtube.com/watch?v=$1', $string); 

    var_dump($string); 
    //string(62) "this is a video http://www.youtube.com/watch?v=erfsdf3445 test" 
?> 

DEMO


另手 - 如果你想使用URL編碼並使用PHP 5.3+可以使用preg_replace_callback與匿名函數:如果您使用任何低於PHP 5

<?php 
    $string = 'this is a video [youtube erfsdf3445] test'; 

    $string = preg_replace_callback('/\[youtube ([^\]]+)\]/', function($match) { 
     return 'http://www.youtube.com/watch?v=' . urlencode($match[1]); 
    }, $string); 

    var_dump($string); 
    //string(62) "this is a video http://www.youtube.com/watch?v=erfsdf3445 test" 
?> 

DEMO


。3,你仍然可以使用preg_replace_callback,只是沒有一個匿名函數:

<?php 
    $string = 'this is a video [youtube erfsdf3445] test'; 

    function replace_youtube_callback($match) { 
     return 'http://www.youtube.com/watch?v=' . urlencode($match[1]); 
    }; 

    $string = preg_replace_callback('/\[youtube ([^\]]+)\]/', 'replace_youtube_callback', $string); 

    var_dump($string); 
    //string(62) "this is a video http://www.youtube.com/watch?v=erfsdf3445 test" 
?> 

DEMO

+0

由於YouTube網址只是字母和數字,您可能甚至不需要回調,只需一個'preg_replace' – ChicagoRedSox

+0

@ChicagoRedSox檢查我幾分鐘前編輯的內容,大約一分鐘前移到頂端。 – h2ooooooo

+0

啊,是的。沒有更新顯示。無論如何,我已經積極參與。 – ChicagoRedSox