Smarty2をPHP7に対応させる方法(The /e modifier is no longer supported Smarty_Compiler.class.php, line 270)

Smartyのversion2をPHP7で動作させると、次のようなエラーが出ます。

Warning (2): preg_replace() [function.preg-replace]: The /e modifier is no longer supported, use preg_replace_callback instead [smarty/libs/Smarty_Compiler.class.php, line 270]

これは正規表現の置き換えpreg_replaceで、修飾子 e が廃止されたために発生するエラーです。

PHPのマニュアルには、修飾子eは廃止されているので、preg_replace_callback()を使うように書かれています。

https://www.php.net/manual/ja/reference.pcre.pattern.modifiers.php#reference.pcre.pattern.modifiers.eval

e (PREG_REPLACE_EVAL)

この機能は PHP 5.5.0 で 非推奨 となり、 PHP 7.0.0 で 削除 されました。
この非推奨の修飾子を設定すると、preg_replace() は、置換文字列において後方参照に関する通常の置換を行った後、 PHP コードとして評価し、検索文字列を置換するためにその結果を 使用します。 置換された後方参照においては、 単引用符や二重引用符、バックスラッシュ (\)および NULL 文字は バックスラッシュでエスケープされます。

この修飾子を使うことはおすすめしません。 リモートから実行可能な脆弱性を作ってしまいがちだからです。 これを防ぐには、preg_replace_callback() 関数を代わりに使うべきです

そこで、preg_replace_callbackを使ったコードに変更する必要がありますが、ここでcreate_function()を使うとdeprecated(非推奨)のエラーが出ます。
create_function()は、PHP7.2.0で非推奨になっているからです。

Deprecated: Function create_function() is deprecated

https://www.php.net/manual/ja/function.create-function.php

create_function
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
create_function 匿名関数 (ラムダ形式) を作成する
この関数は PHP 7.2.0 で 非推奨になります。この関数に頼らないことを強く推奨します。
PHP 5.3.0 以降を使っている場合は、この関数ではなく、ネイティブの 無名関数 を使うべきです。

create_function()のページには、「無名関数を使うべき」と記載があります。

そこで、次のように修正を行うことで非推奨のエラーが出ず、Smarty2を使用することができます。

smarty/libs/Smarty_Compiler.class.php 270行目

$source_content = preg_replace($search.'e', "'"
        . $this->_quote_replace($this->left_delimiter) . 'php'
        . "' . str_repeat(\"\n\", substr_count('\%%BODY%%', \"\n\")) .'"
        . $this->_quote_replace($this->right_delimiter)
        . "'"
    , $source_content);

このコードを次のように書き換えます。

$source_content = preg_replace_callback($search
    , function ($matches) {return $this->_quote_replace($this->left_delimiter) . 'php'
        . str_repeat("\n", substr_count($matches[0], "\n"))
        . $this->_quote_replace($this->right_delimiter);}
    , $source_content); 

ちなみに非推奨のcreate_function()では次のようなコードになります。

$source_content = preg_replace_callback($search
    , create_function ('$matches', "return '"
        . $this->_quote_replace($this->left_delimiter) . 'php'
        . "' . str_repeat(\"\n\", substr_count(\$matches[0], \"\n\")) .'"
        . $this->_quote_replace($this->right_delimiter)
        . "';")
    , $source_content);

関連記事

スポンサーリンク

hgコマンドのヘルプ一覧

ホームページ製作・web系アプリ系の製作案件募集中です。

上に戻る