簡體   English   中英

如何使用正則表達式調用 function 進行字符串替換?

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

我正在開發一個功能,我需要替換一串文本,從中提取參數,然后根據關聯的字符串調用 function。 有點像簡碼系統。

我想允許用戶在{content=whatever}之類的頁面正文中添加文本

然后我想使用該短代碼,並將其替換為 function 調用whatever()我希望它基本上是可擴展的,以便我的代碼將自動調用 function

到目前為止,我讓它以不可擴展的方式工作,所以每當出現新場景時,我都需要添加 if 語句。

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

如您所見,如果我想要不同類型的內容,例如成績、考試等。我需要繼續添加該 if 語句。

任何幫助表示贊賞。 我的正則表達式很差,我一直在https://regexr.com/上,我無法接近我需要的東西。

您可以使用:

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);
}

您可能需要驗證 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);
}

更多關於:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM