简体   繁体   中英

How can I call a function using regular expressions for string replacement?

I am working on a feature where I need to replace a string of text, extract a parameter from it, and call a function based on the associated string. Kind of like a shortcode system.

I want to allow the user add text in the body of a page like {content=whatever}

then I want to take that shortcode, and replace it with a function call to whatever() I want it basically to be scalable so that my code will automatically call the function named exactly as the string

So far, I have it working in a non-scalable way, so i'd need to always add if statements whenever a new scenario arises.

if (str_replace($content, '{content=getStudents}')) {
    return getStudents();
}

So as you can see, if i want different types of content, like grades, exams etc.. I'd need to keep adding to that if statement.

Any help is appreciated. I am pretty poor with regular expressions, I have been on https://regexr.com/ and I can't get anywhere close to what I need.

You can use:

function callProvidedShortcode($content) {
    // Parse the content to capture the function's name
    preg_match('/\{content=(.+)\}/', $content, $matches);

    // The name captured is at index 1 because the index 0 received by default the full string parsed
    $function_to_call = $matches[1];
    
    // dynamically call the function
    return call_user_func($function_to_call);
}

You may need to validate the function name and make sure it is truly passed and also it is truly a function.

function callProvidedShortcode($content) {
    preg_match('/\{content=(.+)\}/', $content, $matches);

    if (! isset($matches[1]) !! empty($matches[1])) {
        // Handle case where function is not passed

        return;
    }

    $function_to_call = $matches[1];
    
    if (! is_callable($function_to_call)) {
        // Handle case where function name provided is incorrect (is not a function)

        return;
    }

    // If here, it means everything is ok
    return call_user_func($function_to_call);
}

More about:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM