CodeIgniter Forums

Full Version: preg_replace_callback
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]easymind[/eluser]
Hi,

this is not really a codeingiter question, but help is often available here and I am developping in CI Smile

The situation:
I have all kinds of texts inside my database. These texts have hyperlinks in them like:

Code:
<a href="!localfile:3,4">link to file</a>

The second digit (the 4) is the id of a file I have also stored in the databse. These files have tags or names also. So what I want is a search throught the text and a replacement where !localfile:3,4 becomes a real link. What I had in mind was:
Code:
preg_replace("/href=\"!localfile:\d,(\d)/",
             '"href=\"".site_url()."downloadfile/".$this->getfiletagbyid($1)',
             $pagetext);

But ofcourse this is not working since you cannot run methods from objects, only functions. I have looked into preg_replace_callback and also call_user_func, bot cannot get it working.

So I need to replace id's in a text with filetags and I do not want to put all files in an array (or something) first.

Hope somebody can help.

Brt

El Forum

[eluser]aart-jan[/eluser]
It's not really a nice solution, but if you can run functions, why don't you make getfiletagbyid a helper(function) and remove it from your object...?

And what's the problem with preg_replace_callback, that seems the function you're looking for.
Why can't you get it to work?

El Forum

[eluser]easymind[/eluser]
Ok well. I did not want to make a helper. But ok, it works now with the helper:

Code:
controller:
-----------
$data['page'] = preg_replace_callback(
            '/href=\"!localfile:\d,(\d)/',
            create_function(
                '$matches',
                'return "href=\"".site_url()."files/showtag/".getfiletag($matches[1]);'
            ),
            $this->mp->getPage($tag)
        );


helper:
-------
function getfiletag($id)
{
    $CI =& get_instance();
    $CI->load->model('model_file','mf');
    $file = $CI->mf->getById($id);
    return $file['tag'];
}