Home > Software design >  Migrate create_function() which is not supported since PHP 7.2
Migrate create_function() which is not supported since PHP 7.2

Time:07-20

I have 'create_function() in my PHP code:

function encode_code_in_comment( $source ) { $encoded = preg_replace_callback( '/\[(php|html|javascript|css|nginx|apache|terminal)\](.*?)\[\/\1\]/ims',

    create_function(
        '$matches',
        '$matches[2] = preg_replace(
              array("/^[\r|\n] /i", "/[\r|\n] $/i"), "",
              $matches[2]);
              return "<pre class=\"language-" . $matches[1] . "\"><code>" . esc_html( $matches[2] ) . "</code></pre>";'
    ),
    $source );

if ( $encoded ) {
    return $encoded;
} else {
    return $source;
}}

I know that there are duplicates threads about the subject, but nevertheless, i'm really struggling to covert this to an anonymous function. How do i rewrite it?

CodePudding user response:

Your main problem is that your code is badly formatted, making it hard to see where the create_function call begins and ends; here it is with some more logical linebreaks and indents:

function encode_code_in_comment( $source ) { 
    $encoded = preg_replace_callback( 
        '/\[(php|html|javascript|css|nginx|apache|terminal)\](.*?)\[\/\1\]/ims',

        create_function(
            '$matches',
            '
                $matches[2] = preg_replace(
                    array("/^[\r|\n] /i", "/[\r|\n] $/i"),
                    "",
                    $matches[2]
                );
                return "<pre class=\"language-" . $matches[1] . "\"><code>" . esc_html( $matches[2] ) . "</code></pre>";
            '
        ),
        
        $source 
    );

    if ( $encoded ) {
        return $encoded;
    } else {
        return $source;
    }
}

From this and the documentation of create_function, we can see that the created function needs one argument, $matches, and to have a body starting $matches[2] = and ending </pre>";

Looking at the manual for anonymous functions we see that the new syntax is function(arguments) { body }, so instead of:

create_function('$matches', ... )

you want:

function($matches) { ... }

and in between, instead of:

'
   $matches[2] = ...
   ... 
   ... </pre>";
'

you want to just remove the quotes and leave the code:

$matches[2] = ...
... 
... </pre>";

The body is in single quotes, and there are no escaped single quotes in there, so the code doesn't need any other changes.

  • Related