如何在PHP正则表达式过滤器中添加条件类

时间:2012-01-23 16:19:44

标签: php regex

下面的代码检测文本正文中的URL并将其包装在标记中。

 function link_it($text)  
    {

        $text= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" >$3</a>", $text);  
        $text= preg_replace("/(^|[\n ])([\w]*?)((www|ftp|m)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" >$3</a>", $text);  
        $text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\">$2@$3</a>", $text);  
        return($text);  
    }  

我想这样,如果用户键入一个url(通过上面的函数检测到)与特定域(flickr | youtube | vimeo)等,该函数添加类“嵌入到标签模板,否则它离开它无阶级。

e.g。

'这是www.google.com'将返回的网站:

this is the website <a href="http://www.google.com">http://www.google.com</a>

但是'这是网站www.flickr.com'将返回

this is the website <a href="http://www.flickr.com" class="embed">http://www.flickr.com</a>

我如何将其添加到函数中?

1 个答案:

答案 0 :(得分:1)

使用preg_replace_callback()。在回调函数中,将URL与应具有embed类的某些URL匹配,如果匹配,则包含class属性定义,否则不包括。