当前位置:  开发笔记 > 编程语言 > 正文

从推文中查找网址,@ replies和#hashtags

如何解决《从推文中查找网址,@replies和#hashtags》经验,为你挑选了1个好方法。

我正在用PHP构建一个Twitter小东西,我正在尝试解析URL,@ replies和#hashtags并将它们变成可点击的链接.

@replies将链接到http://twitter.com/replies

Hashtags想http://search.twitter.com/search?q=%23hashtags

我找到了一个用于解析URL的类,我想知道这是否也可用于解析@replies和#hashtags:

// http://josephscott.org/archives/2008/11/makeitlink-detecting-urls-in-text-and-making-them-links/    
class MakeItLink {
protected function _link_www( $matches ) {
    $url = $matches[2];
    $url = MakeItLink::cleanURL( $url );
    if( empty( $url ) ) {
        return $matches[0];
    }

    return "{$matches[1]}{$url}";
}

public function cleanURL( $url ) {
    if( $url == '' ) {
        return $url;
    }

    $url = preg_replace( "|[^a-z0-9-~+_.?#=!&;,/:%@$*'()x80-xff]|i", '', $url );
    $url = str_replace( array( "%0d", "%0a" ), '', $url );
    $url = str_replace( ";//", "://", $url );

    /* If the URL doesn't appear to contain a scheme, we
     * presume it needs http:// appended (unless a relative
     * link starting with / or a php file).
     */
    if(
        strpos( $url, ":" ) === false
        && substr( $url, 0, 1 ) != "/"
        && !preg_match( "|^[a-z0-9-]+?.php|i", $url )
    ) {
        $url = "http://{$url}";
    }

    // Replace ampersans and single quotes
    $url = preg_replace( "|&([^#])(?![a-z]{2,8};)|", "&$1", $url );
    $url = str_replace( "'", "'", $url );

    return $url;
}

public function transform( $text ) {
    $text = " {$text}";

    $text = preg_replace_callback(
        '#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/\-=?@\[\](+]|[.,;:](?![\s<])|(?(1)\)(?![\s<])|\)))*)#is',
        array( 'MakeItLink', '_link_www' ),
        $text
    );

    $text = preg_replace( '#(]+?>|>))]+?>([^>]+?)#i', "$1$3", $text );
    $text = trim( $text );

    return $text;
}
}

soapergem.. 20

我认为你要做的事情基本上就是我在下面所包含的内容.您transform可以在return语句之前的方法中添加这两个语句.

$text = preg_replace('#@(\w+)#', '$0', $text);
$text = preg_replace('/#(\w+)/', '$0', $text);

这就是你要找的东西吗?



1> soapergem..:

我认为你要做的事情基本上就是我在下面所包含的内容.您transform可以在return语句之前的方法中添加这两个语句.

$text = preg_replace('#@(\w+)#', '$0', $text);
$text = preg_replace('/#(\w+)/', '$0', $text);

这就是你要找的东西吗?

推荐阅读
Gbom2402851125
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有