replace: replacing using %

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


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/">mysite</a> or visit %<a href="http://www.google.com/">google</a>

链接地址: http://www.djcxy.com/p/76720.html

上一篇: php:将所有相关网址转换为绝对网址

下一篇: 替换:替换使用%