需要帮助理解create_function()和regex

时间:2011-07-08 11:58:32

标签: php regex preg-match preg-replace-callback create-function

在围绕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);
}

我还应该提一下,我正在找人给我看正确的代码,我正在寻找有人向我解释为什么我的代码不能正常工作以及我是什么做错了。谢谢您的时间:))

1 个答案:

答案 0 :(得分: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>