1

at the moment I'm looking for a way to call a method from a String. My String looks like this:

"Hello, here's the Link you look for: [[Link,internLink,Go,Login]]."

I'd like to replace [[Link,internLink,Go,Login]] with:

K :: gI('Link')->internLink('Go', 'Login');

Is there a way? The reason is, that I got various texts saved in my Database and I need to call Methods within these texts. Also only the first to parameters (here: Link and internLink) always appear to be class and method. After those two parameters there might be from 0 - XXX parameters, depending on the method.I'm overstrained..

Edit: I tried to work with preg_replace but I'm open for a complete new way if necessary!

Stef
  • 151
  • 1
  • 9

2 Answers2

0
<?php
$subject = "Hello, here's the Link you look for: [[Link,internLink,Go,Login]].";

$result = preg_replace_callback(
        '/\[\[(.*?)]\]/',
        function ($matches) {
            $args = explode(",", $matches[1]);
            $args = array_map("trim", $args);

            $x1 = !empty($args[0])?$args[0]:"default";
            $x2 = isset($args[1])?$args[1]:"default";
            $x3 = "";

            $args = array_slice($args, 2);
            if (count($args) > 0) {
                $x3 = "'" . implode("', '", $args) . "'";
            }
            return "K :: gI('$x1')->$x2($x3);";
        },
        $subject
    );

echo "$result\n";
  • works fine! Only two questions: How can I get php to "run" this method? Like now its converted to the string I need, but can I run it? I tried `eval()` but it wont work and I heard eval is evil... Thats true? – Stef May 03 '15 at 18:05
0

So this is my final method:

PUBLIC function formatClasses($b) {

        $subject = $b;

        $result = 
            preg_replace_callback(
                '/\[\[(.*?)]\]/',
                function ($matches) {
                    $args = explode(",", $matches[1]);
                    $args = array_map("trim", $args);

                    $x1 = !empty($args[0])?$args[0]:"default";
                    $x2 = isset($args[1])?$args[1]:"default";

                    $args = array_slice($args, 2);

                    return call_user_func_array(array(K :: gI($x1), $x2), $args);

                },
                $subject
            );

        return $result;

}

Many thanks to Victor!

Stef
  • 151
  • 1
  • 9