How to loop through, match and replace?

后端 未结 5 643
悲哀的现实
悲哀的现实 2021-01-22 13:10

I have multiple strings with same curly braces I want to replace them as dynamic if I get the count as 1 then need to replace the first occurrence, If count as 2 then replaces t

5条回答
  •  死守一世寂寞
    2021-01-22 13:44

    You can use preg_replace_callback to iterate through your matches.

    e.g.

    $str = "{{ONE}} {{TWO}} {{THREE}} {{FOUR}} {{FIVE}} {{SIX}}";
    $replaced = preg_replace_callback('/{{([^{}]*)}}/', function($match) {
    // $match[1] contains the current match (first capture group) e.g. ONE
    // return your replacement for the current match, e.g. reversed string ENO
    return strrev($match[1]);
    }, $str);
    echo $replaced;
    

    Output will be ENO OWT EERHT RUOF EVIF XIS

提交回复
热议问题