0

您是否知道在 preg_replace 的替换部分中引用对象的任何方法。我试图用对象的属性值替换字符串中的占位符(用百分号分隔)。这将在对象本身中执行,因此我尝试了各种使用 /e 修饰符来引用 $this 的方法。像这样的东西:

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

我无法让这个主题有任何变化。我收到的消息之一是:无法将对象 Model_User 转换为字符串。

但是,当然,将 $this 表示的对象转换为字符串不是我的意图……我想获取与占位符匹配的对象的属性(当然没有百分号)。

我认为我使用 /e 修饰符走在正确的轨道上。但也不完全确定这一点。也许这可以更简单地实现?

有什么想法吗?先感谢您。

4

2 回答 2

2

就像我评论保罗的回答一样:与此同时,我自己找到了解决方案。解决方案比我想象的要简单得多。我不应该使用双引号。

解决方案很简单:

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

希望这可以帮助其他人以供将来参考。

干杯。

于 2009-09-07T16:27:16.000 回答
0

查看preg_replace_callback - 这是您可以如何使用它的方法。

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);

或者,使用 /e 修饰符,你可以试试这个。我认为使它适用于您的情况的唯一方法是将您的对象放入全局范围

$GLOBALS['yourObj']=$this;
$result = preg_replace( '~(%(.*?)%)~e', "\$GLOBALS['yourObj']->\\2", $template );
于 2009-09-07T16:15:39.410 回答