开发者

preg_replace: replacing using %

开发者 https://www.devze.com 2022-12-22 00:33 出处:网络
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.

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>

0

精彩评论

暂无评论...
验证码 换一张
取 消