简体   繁体   English

在PHP中使用正则表达式将文本替换为该文本的功能

[英]replacing text with a function of that text using regex in PHP

I have the text string "[your-name] <[your-email]>" and an Object which contains an array that looks like this 我有文本字符串“ [您的名字] <[您的电子邮件]>”和一个Object,其中包含一个看起来像这样的数组

  [posted_data] => Array
        (
            [_wpcf7] => 35
            [_wpcf7_version] => 3.5.2
            [_wpcf7_locale] => en_US
            [_wpcf7_unit_tag] => wpcf7-f35-p29-o1
            [_wpnonce] => 2c06b3f0f3
            [your-name] => Andrew
            [your-email] => fr@ibhv.cou
            [your-subject] => plasd
            [your-message] => 11 11 11
            [_wpcf7_is_ajax_call] => 1
        )

So what I want to do is write a function that replaces the text in the above string with the values from the object. 所以我想做的是编写一个函数,用对象中的值替换上面字符串中的文本。

So far I have this function 到目前为止,我有这个功能

function wpcf7ev_get_senders_email_address($wpcf7_form)
{
    //gets the tags
    $senderTags = $wpcf7_form->mail['sender'];

    // replace <contents> with posted_data

    $sendersEmailAddress = preg_replace_callback('/\[(.+?)\]/',
             function ($matches)
             {
                return $wpcf7_form->posted_data[$matches[1]];
             },
             $senderTags
             );

    return $sendersEmailAddress;

}

Am I going about this the right way? 我要这样做正确吗? That callback function fails because the anonymous function doesn't have access to the $wpcf7_form parameter it seems. 该回调函数失败,因为匿名函数似乎无权访问$ wpcf7_form参数。

I'm using matches[1] as that regular expression returns 我正在使用matchs [1],因为该正则表达式返回

Array
(
    [0] => [your-name]
    [1] => your-name
)

So maybe that could be improved on too. 因此,也许可以对此进行改进。

Thanks. 谢谢。

Pass any dependencies in via the use construct, eg 通过use构造传递任何依赖,例如

function ($matches) use ($wpcf7_form) {
    // etc

Create a helper class and pass it as callback parameter. 创建一个帮助器类,并将其作为回调参数传递。 This way you could avoid using global parameter. 这样,您可以避免使用全局参数。

class EmailAddressCallback {
    private $data;

    function __construct($data) {
        $this->data = $data;
    }

    public function callback_function($matches) {
        return $this->data->posted_data[$matches[1]];
    }
}

function wpcf7ev_get_senders_email_address($wpcf7_form)
{
    //gets the tags
    $senderTags = $wpcf7_form->mail['sender'];

    // replace <contents> with posted_data

    $callback = new EmailAddressCallback($wpcf7_form);
    $sendersEmailAddress = preg_replace_callback('/\[(.+?)\]/',
             array($callback, 'callback_function'),
             $senderTags
             );

    return $sendersEmailAddress;

}

var_dump(htmlentities(wpcf7ev_get_senders_email_address($wpcf7_form)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM