preg_replace() 带有 e 修饰符:替换中的引用对象
您知道有什么方法可以在 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 修饰符我走在正确的轨道上。但对此也不完全确定。也许这可以更简单地实现?
对此有什么想法吗?先感谢您。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就像我对保罗的回答的评论一样:同时我自己找到了解决方案。解决方案比我想象的要简单得多。我不应该使用双引号。
解决方案就像这样简单:
希望这对其他人有帮助以供将来参考。
干杯。
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:
Hope this helps anyone else for future reference.
Cheers.
查看 preg_replace_callback - 以下是您可以如何使用它。
或者,使用 /e 修饰符,您可以尝试这个。我认为使它适合您的情况的唯一方法是将您的对象放入全局范围
Check out preg_replace_callback - here's how you might use it.
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