1

我有文本字符串“[your-name] <[your-email]>”和一个包含如下数组的对象

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

所以我想做的是编写一个函数,用对象中的值替换上面字符串中的文本。

到目前为止我有这个功能

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;

}

我会以正确的方式解决这个问题吗?该回调函数失败,因为匿名函数似乎无权访问 $wpcf7_form 参数。

我正在使用matches [1]作为正则表达式返回

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

所以也许这也可以改进。

谢谢。

4

2 回答 2

0

通过use构造传递任何依赖项,例如

function ($matches) use ($wpcf7_form) {
    // etc
于 2013-10-02T01:09:49.440 回答
0

创建一个辅助类并将其作为回调参数传递。这样你就可以避免使用全局参数。

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)));
于 2013-10-02T02:30:14.740 回答