3

次のテキストがあります

"I made this video on my birthday. All of my friends are here in party. Click play to video the video
 http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit "

私が欲しいのは、これを上記のURLに置き換えることです

"I made this video on my birthday. All of my friends are here in party. Click play to video the video

      <iframe width="853" height="480" src="http://www.youtube.com/embed/G3j6avmJU48" frameborder="0" allowfullscreen></iframe> "

次のスクリプトで上記の URL から YouTube ビデオ ID を取得できることはわかっています。

     preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $word, $matches);


        $youtube_id = $matches[0];

しかし、URLを置き換える方法がわかりません

http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit

  <iframe width="853" height="480" src="http://www.youtube.com/embed/G3j6avmJU48" frameborder="0" allowfullscreen></iframe>

助けてくださいありがとう

4

2 に答える 2

1

preg_replace 関数を使用します ( PHP preg_replace() ドキュメント を参照) 。

編集 :

preg_replace の使用は次のとおりです。括弧 () を使用して正規表現 (最初のパラメーター) でキャプチャしたいものをラップし、2 番目のパラメーターで $n (n は正規表現の括弧の順序) を使用して、キャプチャしたものを取得します。 .

あなたの場合、次のようなものが必要です:

$text = "I made this video on my birthday. All of my friends are here in party. Click play to video the video http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit";

$replaced = preg_replace('#http://www\.youtube\.com/watch\?v=(\w+)[^\s]+#i','<iframe width="853" height="480" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>',$text);

より高度な使用法と例については、以前に提供したドキュメント リンクを参照してください。

これがさらに役立つことを願っています。

編集 2: 正規表現が間違っていたので、修正しました。

于 2012-08-01T21:22:53.697 に答える
0

@Matt コメントに基づいて、このサンプル コードを使用してそれを実現できます。

<?php
$text = "I made this video on my birthday. All of my friends are here in party. Click play to video the video
 http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit ";

$rexProtocol = '(https?://)?';
$rexDomain   = '(www\.youtube\.com)';
$rexPort     = '(:[0-9]{1,5})?';
$rexPath     = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?';
$rexQuery    = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
$rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';

function callback($match)
{
    $completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
    $videoId = array ();
    preg_match ("|\?v=([a-zA-Z0-9]*)|", $match[5], $videoId);

    return '<iframe src="http://www.youtube.com/embed/' . $videoId[1] . '" width="853" height="480"></iframe>';
}
print preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&", 'callback', htmlspecialchars($text));

?>
于 2012-08-01T21:43:23.060 に答える