使用 PHP 中的正则表达式将该文本的函数替换文本


replacing text with a function of that text using regex in PHP

我有文本字符串"[你的姓名] <[你的电子邮件]>"和一个包含如下所示的数组的对象

  [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;
}

我这样做的方式是否正确?该回调函数失败,因为匿名函数似乎无法访问 $wpcf 7_form 参数。

我正在使用匹配[1],因为正则表达式返回

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

所以也许这也可以改进。

谢谢。

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

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

创建一个帮助程序类并将其作为回调参数传递。这样,您可以避免使用全局参数。

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