preg_match - 这段代码有什么问题?

preg_match - what's wrong with this code?

$message 包含两个不同的 Youtube 视频。下面的代码有效,但问题是最终结果会产生两个具有相同视频 ID 的 iframe(第一个视频)。我该如何解决这个问题?

$message = 'This is a text with 2 Youtube videos: https://www.youtube.com/watch?v=rxwMjB-Skao csassasas http://www.youtube.com/watch?v=VWEwWECAokU Enf of text';

$reg_exUrl_youtube = "/(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'> \r\n]+)(?![^<]*>)/";
if (preg_match($reg_exUrl_youtube, $message, $youtubeUrlData) ) {
$message = preg_replace($reg_exUrl_youtube, "<iframe title=\"{$youtubeUrlData[1]}\" class=\"youtube\" src=\"[qqqqq].youtube.com/embed/{$youtubeUrlData[1]}\" frameborder=\"0\" allowFullScreen></iframe>", $message);
}

为什么要使用容易出错的正则表达式?

更简单:

$message = 'This is a text with 2 Youtube videos: https://www.youtube.com/watch?v=rxwMjB-Skao csassasas http://www.youtube.com/watch?v=VWEwWECAokU Enf of text';

$a=explode(' ',$message);
foreach($a as $v){
    if(strpos($v,'http')!==false && strpos($v,'youtube')!==false){
    $res[]=$v;
    }
}   
echo var_dump($res);

1) 您的代码的修复方法 是在 preg_replace[=19] 中使用 $1 而不是 {$youtubeUrlData[1]} =]() 呼叫:

$message = preg_replace($reg_exUrl_youtube, "<iframe title=\"\" class=\"youtube\" src=\"[qqqqq].youtube.com/embed/\" frameborder=\"0\" allowFullScreen></iframe>", $message);

2) preg_replace_callback() 的另一种实现,根据我的经验,这是非常可靠的,举个例子:

$message = 'This is a text with 2 Youtube videos: https://www.youtube.com/watch?v=rxwMjB-Skao csassasas http://www.youtube.com/watch?v=VWEwWECAokU Enf of text';

$reg_exUrl_youtube = "/(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'> \r\n]+)(?![^<]*>)/";

$finalString = preg_replace_callback($reg_exUrl_youtube, function($matches) {
    return "<iframe title=\"{$matches[1]}\" class=\"youtube\" src=\"[qqqqq].youtube.com/embed/{$matches[1]}\" frameborder=\"0\" allowFullScreen></iframe>";
}, $message);

echo htmlentities($finalString);