Php 使用链接或youtube链接等帖子的博客

Php 使用链接或youtube链接等帖子的博客,php,preg-replace,Php,Preg Replace,我用php创建了一个博客。用户可以发布任何内容,如文本、链接或youtube链接。我使用preg_replace来确定何时存在链接或youtube链接。这就是我使用的: <?php //...code $row['comment'] = preg_replace('@(https?://([-\w.]+[-\w])+(:\d+)?(/([\w-.~:/?#\[\]\@!$&\'()*+,;=%]*)?)?)@', '<a href="$1" target="_blank

我用php创建了一个博客。用户可以发布任何内容,如文本、链接或youtube链接。我使用preg_replace来确定何时存在链接或youtube链接。这就是我使用的:

<?php

//...code


$row['comment'] = preg_replace('@(https?://([-\w.]+[-\w])+(:\d+)?(/([\w-.~:/?#\[\]\@!$&\'()*+,;=%]*)?)?)@', '<a href="$1" target="_blank">$1</a>', $row['comment']);


$row['comment'] = preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i"," <object width=\"100px;\" height=\"100px;\"><param name=\"movie\" value=\"http://www.youtube.com/v/$1&hl=en&fs=1\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"http://www.youtube.com/v/$1&hl=en&fs=1\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"400px;\" height=\"200px;\"></embed></object>",$row['comment']);

  // then prints the $row['comment']

 ?>
我的preg_replace运行良好,并能成功确定何时存在链接或youtube链接。唯一的问题是,当发布youtube链接时,它会显示两次……可能是因为我为$row['comment']提供了两种不同的声明。你知道我该怎么处理这个吗?将上述两种陈述合并为1是否更好?我该怎么做?或者我可以使用的任何其他if语句


您知道如何将上述两条语句组合在一起吗?

我更喜欢使用strpos函数来检查案例url中的字符串。有关更多详细信息,请参阅文档


建议使用if结构,因为您需要为每种链接类型执行不同的实现。下面的代码非常有用。

下面的代码将实现这一功能

function get_link_type($url)
{
    if(strpos($url, 'youtube') > 0)
    {
        return 'youtube';
    }
    else
    {
        return 'default';
    }
}

$url = 'http://www.google.com/watch?v=rj18UQjPpGA&feature=player_embedded';
$link_type = get_link_type($url);

if($link_type == 'youtube')
{
    $new_link = '<iframe width="560" height="315" src="//'. $url .'" frameborder="0" allowfullscreen></iframe>';
}
else
{
    $new_link = '<a href="'. $url .'">'. $url .'</a>';
}

echo $new_link;

首先检查它是否是youtube链接如果不是检查链接知道如何编写吗?youtube正则表达式应该排除已链接的链接。看起来不错知道如何执行我的代码吗?知道如何使用此函数修改代码吗?