Replace several words in string using associative array keeping original case intact

后端 未结 2 1424
春和景丽
春和景丽 2021-01-21 07:41

I want to match an array against a text string where words matching with the array keys will be replaced by a span tag with a title with the matching array value.

I can

2条回答
  •  抹茶落季
    2021-01-21 08:27

    You can achieve it with some common PHP functions.

    1. Create an array of patterns from your keys to search in a case-insensitive manner with preg_replace_callback.

    2. Pass the $glossary to the anonymous function in preg_replace_callback and get the value (the title) by the lowercased current match value, and once found, replace the lowercase wordX with the match.

    This is PHP code:

    $pttrns = array_map(function ($val) {return "/" . preg_quote($val) . "/i"; },
                      array_keys($glossary));                                    // Step 1
    $res = preg_replace_callback($pttrns, function ($m) use($glossary){          // Step 2
        return str_replace(strtolower($m[0]), $m[0],              
                                         $glossary[strtolower($m[0])]);         // Step 3
    }, $text);
    

提交回复
热议问题