简体   繁体   English

如何使用正则表达式调用 function 进行字符串替换?

[英]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.我正在开发一个功能,我需要替换一串文本,从中提取参数,然后根据关联的字符串调用 function。 Kind of like a shortcode system.有点像简码系统。

I want to allow the user add text in the body of a page like {content=whatever}我想允许用户在{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然后我想使用该短代码,并将其替换为 function 调用whatever()我希望它基本上是可扩展的,以便我的代码将自动调用 function

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 语句。

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.如您所见,如果我想要不同类型的内容,例如成绩、考试等。我需要继续添加该 if 语句。

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.我的正则表达式很差,我一直在https://regexr.com/上,我无法接近我需要的东西。

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 名称并确保它真正通过并且它确实是 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:更多关于:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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