views:

256

answers:

2

Hi all,

Do you know of any way to reference an object in the replacement part of preg_replace. I'm trying to replace placeholders (delimited with precentage signs) in a string with the values of attributes of an object. This will be executed in the object itself, so I tried all kinds of ways to refer to $this with the /e modifier. Something like this:

/* for instance, I'm trying to replace
 * %firstName% with $this->firstName
 * %lastName% with $this->lastName
 * etc..
 */
$result = preg_replace( '~(%(.*?)%)~e', "${'this}->{'\\2'}", $template );

I can't get any variation on this theme to work. One of the messages I've been getting is: Can't convert object Model_User to string.

But of course, it's not my intention to convert the object represented by $this to a string... I want to grab the attribute of the object that matches the placeholder (without the percentage signs of course).

I think I'm on the right track with the /e modifier. But not entirely sure about this either. Maybe this can be achieved much more simple?

Any ideas about this? Thank you in advance.

A: 

Check out preg_replace_callback - here's how you might use it.

class YourObject
{

    ...

    //add a method like this to your class to act as a callback
    //for preg_replace_callback...
    function doReplace($matches) 
    {
        return $this->{$matches[2]};
    }

}

//here's how you might use it
$result = preg_replace_callback(
    '~(%(.*?)%)~e', 
    array($yourObj, "doReplace"), 
    $template);

Alternatively, using the /e modifier, you could maybe try this. I think the only way to make it work for your case would be to put your object into global scope

$GLOBALS['yourObj']=$this;
$result = preg_replace( '~(%(.*?)%)~e', "\$GLOBALS['yourObj']->\\2", $template );
Paul Dixon
Hi Paul,Thank you for the pointer. But I'm aware of preg_replace_callback already. I was hoping this could be achieved without it. Do you think this is possible? I think it should, but can't get the correct syntax.
fireeyedboy
Hi Paul, thanks again for your effort. But as you will often see: if you give it another try you find the solution after you've asked the question. In this case I found the solution too. :-/ It was much more simple than I thought. I'll post the solution here as an answer.
fireeyedboy
A: 

Like I commented to Paul's answer: in the meanwhile I found the solution myself. The solution is much more simple than I thought. I shouldn't have used double quotes.

The solution is as simple as this:

$result = preg_replace( '~(%(.*?)%)~e', '$this->\\2', $template );

Hope this helps anyone else for future reference.

Cheers.

fireeyedboy
I've learned something too - I'm amazed the $this reference works in this case!
Paul Dixon
Well, then I guess my question wasn't in vain after all. :) Cheers.
fireeyedboy