0

在搜索了 SO 和其他论坛也绊倒了各种 php 函数文档之后,我尝试编辑我在这里找到的一个函数(将 URL 转换为可点击的链接),这样它也可以处理嵌入式视频,不幸的是我的技能组合很差,而且我相信我不完全理解create_function()要在这方面取得成功。

所以这是我的炒鸡蛋代码:

private function _check4Links($text){
    $pattern  = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
    $callback = create_function('$matches', '
       $url       = array_shift($matches);
       $url_parts = parse_url($url);

       if(preg_match("%(?:youtube\.com/(?:user/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i", $url, $match)){
            return sprintf(\'<iframe title="YouTube video player" class="youtube-player" type="text/html" width="400" height="244" src="http://www.youtube.com/embed/\'.$match[1].\'" frameborder="0" allowFullScreen></iframe>\', $url, $text);
       }else{

            $text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
            $text = preg_replace("/^www./", "", $text);

            $last = -(strlen(strrchr($text, "/"))) + 1;
            if ($last < 0) {
               $text = substr($text, 0, $last) . "&hellip;";
            }

            return sprintf(\'<a target="_blank"rel="nofollow" href="%s">%s</a>\', $url, $text);
       }');

    return preg_replace_callback($pattern, $callback, $text);
}

我还应该提一下,我不是在找人来向我展示正确的代码,而是在找人向我解释为什么我的代码不起作用以及我做错了什么。感谢您的时间 :)

4

1 回答 1

2

这是一个修复:

<?php
function _check4Links($text){
    $pattern  = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';

    return preg_replace_callback($pattern, 'fnc', $text);
}

function fnc($matches) {
    $url       = array_shift($matches);
    $url_parts = parse_url($url);

    if(preg_match("%(?:youtube\.com/(?:user/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^\"&?/ ]{11})%i", $url, $match)){
          return '<iframe title="YouTube video player" class="youtube-player" type="text/html" width="400" height="244" src="http://www.youtube.com/embed/'.$match[1].'" frameborder="0" allowFullScreen></iframe>';
    } else {

        $text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
        $text = preg_replace("/^www./", "", $text);

        $last = -(strlen(strrchr($text, "/"))) + 1;
        if ($last < 0) {
            $text = substr($text, 0, $last) . "&hellip;";
        }

        return sprintf('<a target="_blank"rel="nofollow" href="%s">%s</a>', $url, $text);
        }
    }

$txt = <<<TXT
Let's do some tests!
http://www.google.com
http://www.youtube.com/watch?v=L25R4DR79mU
TXT;

echo _check4Links($txt);
?>

输出是:

Let's do some tests!
<a target="_blank"rel="nofollow" href="http://www.google.com">google.com</a>
<iframe title="YouTube video player" class="youtube-player" type="text/html" width="400" height="244" src="http://www.youtube.com/embed/L25R4DR79mU" frameborder="0" allowFullScreen></iframe>
于 2011-07-08T13:23:37.050 回答