Replace words found in string with highlighted word keeping their case as found

后端 未结 2 706
长发绾君心
长发绾君心 2020-12-20 06:49

I want to replace words found in string with highlighted word keeping their case as found.

Example

$string1 = \'There are five color         


        
2条回答
  •  轮回少年
    2020-12-20 07:01

    To highlight a single word case-insensitively

    Use preg_replace() with the following regex:

    /\b($p)\b/i
    

    Explanation:

    • / - starting delimiter
    • \b - match a word boundary
    • ( - start of first capturing group
    • $p - the escaped search string
    • ) - end of first capturing group
    • \b - match a word boundary
    • / - ending delimiter
    • i - pattern modifier that makes the search case-insensitive

    The replacement pattern can be $1, where $1 is a backreference — it would contain what was matched by the first capturing group (which, in this case, is the actual word that was searched for)

    Code:

    $p = preg_quote($word, '/');  // The pattern to match
    
    $string = preg_replace(
        "/\b($p)\b/i",
        '$1', 
        $string
    );
    

    See it in action


    To highlight an array of words case-insensitively

    $words = array('five', 'colors', /* ... */);
    $p = implode('|', array_map('preg_quote', $words));
    
    $string = preg_replace(
        "/\b($p)\b/i", 
        '$1', 
        $string
    );
    
    var_dump($string);
    

    See it in action

提交回复
热议问题