PHP using prefix tags to linkify text

Go To StackoverFlow.com

0

I'm trying to write a code library for my own personal use and I'm trying to come up with a solution to linkify URLs and mail links. I was originally going to go with a regex statement to transform URLs and mail addresses to links but was worried about covering all the bases. So my current thinking is perhaps use some kind of tag system like this:

l:www.google.com becomes http://www.google.com and where m:john.doe@domain.com becomes john.doe@domain.com.

What do you think of this solution and can you assist with the expression? (REGEX is not my strong point). Any help would be appreciated.

2012-04-04 02:01
by greentiger


0

Maybe some regex like this :

$content = "l:www.google.com some text m:john.doe@domain.com some text";
$pattern = '/([a-z])\:([^\s]+)/'; // One caracter followed by ':' and everything who goes next to the ':' which is not a space or tab
if (preg_match_all($pattern, $content, $results))
{
    foreach ($results[0] as $key => $result)
    {
        // $result is the whole matched expression like 'l:www.google.com'
        $letter = $results[1][$key];
        $content = $results[2][$key];

        echo $letter . ' ' . $content . '<br/>';
        // You can put str_replace here
    }
}
2012-04-04 02:24
by mamadrood
Thanks I will have to test this when I actually get some time :- - greentiger 2012-04-05 02:07
I don't understand why you chose this particular method, would something like preg_replace("/l\:([^\s]+)/", "$1", $string) be better? I'm thinking '^\s' is a string that is terminated by a white space character - greentiger 2012-04-05 02:17
Yes, but you want to do something like m:john.doe@domain.com and transform it to a mailto, so you need to get the first letter too. and [^\s]+ is a string without blank caracter (\s) (space, tab, line feed, etc...) - mamadrood 2012-04-05 13:55
I didn't use this solution but it did lead me down another way of thinking--so I'm going to consider this closed. Thanks - greentiger 2012-04-06 00:07