2012-05-03 2 views
3

こんにちは私はYouTubeのリンクを埋め込みコードに変換しようとしています。preg_replace()で埋め込むすべてのYouTube URLを交換してください

これは私が持っているものです。

<?php 

$text = $post->text; 

    $search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*$#x'; 
    $replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></center>'; 
    $text = preg_replace($search, $replace, $text); 


echo $text; 
?> 

それは一つのリンクのために働きます。しかし、2つを追加すると、最後のオカレンスだけが交換されます。私は何を変えなければならないのですか?

答えて

6

文字列の最後を正しく処理していません。 $を削除し、終了タグ</a>に置き換えます。これで修正されます。ここで

$search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*<\/a>#x'; 
$replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></center>'; 
$text = preg_replace($search, $replace, $text); 
+0

感謝を!私はそれらの正規表現の記号すべてでそれを見逃しているに違いない。 – Axel

+0

確かに、正規表現ドメインの欲張りの意味も分かりません。 – hakre

0

このお試しください:

EDIT働いていない場合はことを試してみてください...私はそれがデフォルトだ知っているが、誰もが知っているpreg_replace($search, $replace, $text, -1);

を。

do{ 
    $text = preg_replace($search, $replace, $text, -1, $Count); 
} 
while($Count); 
0

は、より効率的な定期expresionです:http://pregcopy.com/exp/26、PHPにこれをtralate:(修飾子を "s" を追加)

<?php 

$text = $post->text; 

    $search = '#<a (?:.*?)href=["\\\']http[s]?:\/\/(?:[^\.]+\.)*youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)([\w\-\_]+)["\\\']#ixs'; 
    $replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe></center>'; 

    $text = preg_replace($search, $replace, $text); 


echo $text; 
?> 

テストを

関連する問題