views:

46

answers:

1

Hi all, I'm using the function preg_replace but I cannot figure out how to make it work, the function just doesn't seem to work for me.

What I'm trying to do is to convert a string into a link if any word contains the % (percentage) character.

For instance if I have the string "go to %mysite", I'd like to convert the mysite word into a link. I tried the following...

$data = "go to %mysite";
$result = preg_replace('/(^|[\s\.\,\:\;]+)%([A-Za-z0-9]{1,64})/e', 
          '\\1%<a href=#>\\2</a>', $data);

...but it doesn't work.

Any help on this would be much appreciated.

Thanks

Juan

+3  A: 

The problem here is e modifier which evaluates the replacement as php code and fails with fatal error


Removing e attribute will output go to %<a href=#>mysite</a> and if it is desired result, you don't have to change anything else.

But I think that preg_replace_callback is what you really need, ie:

function createLinks($matches)
{
    switch($matches[2])
    {
        case 'mysite':
            $url = 'http://mysite.com/';
            break;
        case 'google':
            $url = 'http://www.google.com/';
            break;
    }

    return "{$matches[1]}%<a href=\"{$url}\">{$matches[2]}</a>";
}

$data = "go to %mysite or visit %google";
$data = preg_replace_callback(
    '/(^|[\s\.\,\:\;]+)%([A-Za-z0-9]{1,64})/',
    'createLinks',
    $data
);

that will result in go to %<a href="http://mysite.com/"&gt;mysite&lt;/a&gt; or visit %<a href="http://www.google.com/"&gt;google&lt;/a&gt;

dev-null-dweller
Hi dev-null-dweller, thank you for your answer. Do you know how I can fix this issue? Do I have to use the e modifier?ThanksJuan
Juan
You don't have, check my edited answer for more details
dev-null-dweller
Thanks dev-null-dweller, this is exactly what I'm aiming for. I'll give it a try. Thanks again
Juan