Multiple replace (probably preg_replace) of same string with array

前端 未结 2 757
别那么骄傲
别那么骄傲 2021-01-16 04:06

I need to replace multiple instances of a certain string (question mark) with strings from an array. e.g. if the string I wish to replace appears 3 times and my array has a

2条回答
  •  走了就别回头了
    2021-01-16 04:53

    It gets a little ugly in PHP 5.2 because you have to use global variables to pass information between callbacks but it's very flexible otherwise. Use preg_replace_callback():

    preg_replace_callback('!\?!', 'rep_array', $myString);
    
    $i = 0;
    
    function rep_array($matches) {
      global $myArray;
      return $myArray[$i++];
    }
    

    You'd have to cater for there being more ?s than array entries as well as reset the counter with each call.

    Adam is right about sprintf() being somewhat cleaner but you don't always control the input string. preg_replace_callback can cater for a far wider range of circumstances.

提交回复
热议问题