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

后端 未结 2 1425
春和景丽
春和景丽 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 <span> 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);
    
    0 讨论(0)
  • 2021-01-21 08:36

    You can run this replace in loop:

    $txt = 'Hi! How are you doing? Have some stars: * * *!';
    $glossary = array(
        'Hi!'   => 'title 1',
        'stars' => 'title 2',
        '*'     => 'title 3'
    );
    $result = $txt;
    foreach ($glossary as $keyword => $title) {
        $pattern = '#(?<=^|\W)('.preg_quote($keyword).')(?=$|\W)#i';
        $result  = preg_replace($pattern, "<span title='{$title}'>$1</span>", $result);
    }
    echo $result;
    
    0 讨论(0)
提交回复
热议问题