PHPのエラー解決: Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /usr/share/pear/Mail/mimeDecode.php on line 762

PEARのMailライブラリを使ってるんだけど、PHP5にしたらDeprecatedエラーが毎回出てるのでなんとかしよう。
(※検索すると「PHPのエラーレベルを下げてDeprecateエラーを出力しないようにすれば解決」とかIQもモラルもリテラシーも低いことを書いているブログもありますが、非推奨ってことはいずれ廃止されたときに、PHPがアップデートされた瞬間に動かなくなる危険性があるので、そういう適当な対応は非推奨です。)

エラーメッセージを真面目に読むと

エラー原文

PHP Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /usr/share/pear/Mail/mimeDecode.php on line 762

広告

日本語訳

PHP Deprecated: preg_replace(): 「/e」修飾子は非推奨なので、代わりに「preg_replace_callback」を使いなさい。場所は /usr/share/pear/Mail/mimeDecode.php の 762行目。

ご丁寧に推奨関数を教えてくれているので、おとなしく指示に従う。

/**
 * Given a quoted-printable string, this
 * function will decode and return it.
 *
 * @param  string Input body to decode
 * @return string Decoded body
 * @access private
 */
function _quotedPrintableDecode($input)
{
    // Remove soft line breaks
    $input = preg_replace("/=\r?\n/", '', $input);
 
    // Replace encoded characters
            $input = preg_replace('/=([a-f0-9]{2})/ie', "chr(hexdec('\\1'))", $input);
    return $input;
}

問題の箇所はこの、エンコード済みの文字を置換している部分。オプション修飾子の[e]が非推奨になっているのだ。

$input = preg_replace('/=([a-f0-9]{2})/ie', "chr(hexdec('\\1'))", $input);

ご推奨のpreg_replace_callbackで書き換えると次のようになる。

$input = preg_replace_callback('/=([a-f0-9]{2})/i', function($m) { return chr(hexdec($m[0])); }, $input);
/**
 * Given a quoted-printable string, this
 * function will decode and return it.
 *
 * @param  string Input body to decode
 * @return string Decoded body
 * @access private
 */
function _quotedPrintableDecode($input)
{
    // Remove soft line breaks
    $input = preg_replace("/=\r?\n/", '', $input);
 
    // Replace encoded characters
            //$input = preg_replace('/=([a-f0-9]{2})/ie', "chr(hexdec('\\1'))", $input);
            $input = preg_replace_callback('/=([a-f0-9]{2})/i', function($m) { return chr(hexdec($m[0])); }, $input);
    return $input;
}

これにてエラー解消。

About: dacelo


Leave a Reply

Your email address will not be published. Required fields are marked *