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

后端 未结 2 1431
春和景丽
春和景丽 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: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, "$1", $result);
    }
    echo $result;
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题