preg_match - 这段代码出了什么问题?

时间:2015-03-07 12:43:29

标签: php preg-match

$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);
}

2 个答案:

答案 0 :(得分:1)

1)代码修复是在 preg_replace ()调用中使用$ 1而不是{$ youtubeUrlData [1]}:

$message = preg_replace($reg_exUrl_youtube, "<iframe title=\"$1\" class=\"youtube\" src=\"[qqqqq].youtube.com/embed/$1\" 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);

答案 1 :(得分:-1)

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

更简单:

$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);