How to loop through, match and replace?

后端 未结 5 571
悲哀的现实
悲哀的现实 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:36

    The expression we might wish to design here can be like one of these:

    ({{)(.+?)(}})
    

    which is only using capturing groups ().

    DEMO 1


    (?:{{)(.+?)(?:}})
    

    and here we can use non-capturing groups (?:), if we do not wish to keep the {{ and }}.

    DEMO 2

    Then, we could simply do the preg_replace that we wanted to do.

    Test

    $re = '/(?:{{)(.+?)(?:}})/m';
    $str = '{{ONE}} {{TWO}} {{THREE}} {{FOUR}} {{FIVE}} {{SIX}}';
    $subst = '$1';
    
    $result = preg_replace($re, $subst, $str);
    
    echo "The result of the substitution is ".$result;
    

提交回复
热议问题