Preg_replace a specific strings first character

38 Views Asked by At

I have a string of "You can go to kitchen and get some food for your dinner" and i need to change with preg_replace words You, your, food case insensitive to <i>y</i>ou,<i>y</i>our,<i>f</i>ood

Is there i a pattern to match first character of a specific words in the string? Can someone give examples

input text not matching

1

There are 1 best solutions below

1
Sammitch On

You can generalize the pattern to just match words using the \b word boundary class, use preg_replace_callback(), and a list of target words to make this more easily extensible. Eg:

$input = "You can go to kitchen and get some food for your dinner";

$pattern ='/\b(\w)(\w+)\b/i';

$whitelist = ['you', 'your', 'food'];

$output = preg_replace_callback(
    $pattern,
    function($a)use($whitelist){
        if( in_array(strtolower($a[0]), $whitelist) ) {
            return sprintf('<i>%s<\i>%s', $a[1], $a[2]);
        } else {
            return $a[0];
        }
    },
    $input
);

var_dump($output);

Output:

string(76) "<i>Y<\i>ou can go to kitchen and get some <i>f<\i>ood for <i>y<\i>our dinner"