Replace the contents of several divs with several callbacks in PHP

1

I am trying to replace the content that exists within several divs with several callbacks. The name of the callbacks I want to use are within those divs:

function googlemaps(){
    return 'Google Maps muestra su contenido'
}

function socialicons(){
    return 'Social Icons muestra su contenido';
}

function callaction(){
    return 'Call Action hace sus cosas y muestra su contenido';
}

$builder = '
    <div class="row">
        <div class="column col-md-4 col-sm-4 col-xs-4">
            <!--moz-module-->
            <div class="moz-widget">
            <div class="moz-widget-id">[moz_widget]googlemaps[/moz_widget]</div>
            </div>
            <!--/moz-module-->
        </div>

        <div class="column col-md-4 col-sm-4 col-xs-4">
            <!--moz-module-->
            <div class="moz-widget">
            <div class="moz-widget-id">moz_widget]videos[/moz_widget</div>
            </div>
            <!--/moz-module-->
        </div>

        <div class="column col-md-4 col-sm-4 col-xs-4">
            <!--moz-module-->
            <div class="moz-widget">
            <div class="moz-widget-id">[moz_widget]postsgrid[/moz_widget]</div>
            </div>
            <!--/moz-module-->
        </div>
    </div>
';

$builder = preg_replace_callback('/(<div.*?class="moz-widget-id"[^>]*>)(.*?)(<\/div>)/i', function($matches) {
    $matches[0]();
}, $builder);

The result I get after running the code is a fatal error:

  

Fatal error: Call to undefined function [moz_widget] googlemaps [/ moz_widget] ()   in ...

    
asked by Infobuscador 17.05.2016 в 23:37
source

1 answer

0

In your original code, brackets [] were missing and the functions were not called well.

But that was not the main problem, if not your regex did not work well and the output was:

[moz_widget]googlemaps[\/moz_widget]

Regex Demo

with which it could not call the functions correctly and responded with an error.

With the new regex /\[.*\](.*?)\[.*\]/ you eliminate all the brackets [] with their content and that's when you call your functions correctly:

Demo working in PHP

See new Regex

$nuevoContenido = preg_replace_callback('/\[.*\](.*?)\[.*\]/i', function($matches) {

    return $matches[1]();

}, $builder);

echo $nuevoContenido;
    
answered by 18.05.2016 / 02:09
source