gordyr
gordyr

Reputation: 6276

How to add conditional class into PHP regex filter

The code below detects URL's in a body of text and wraps them in tags.

 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);  
    }  

I would like it so that if a user types a url (detected via the function above) with a specific domain of (flickr|youtube|vimeo) etc the function adds the class "embed to the tag template, otherwise it leaves it classless.

e.g.

'this is the website www.google.com' would return:

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

but 'this is the website www.flickr.com' would return

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

How would I go about adding this into the function?

Upvotes: 1

Views: 155

Answers (1)

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28899

Use preg_replace_callback() for this. In your callback function, match the URL against some set of URLs that should have the embed class, and if it matches, include the class attribute definition, otherwise don't.

Upvotes: 1

Related Questions