Parse through a string php and replace substrings

前端 未结 2 983
忘掉有多难
忘掉有多难 2021-01-23 06:00

I have a string, in PHP and the string has occurrences of the pattern %%abc%%(some substring)%%xyz%%

There are multiple occurrences of such substrings withi

相关标签:
2条回答
  • 2021-01-23 06:21

    Use preg_replace_callback(), like this:

    preg_replace_callback( '#%%abc%%(.*?)%%xyz%%#', function( $match) {
        // Do some logic (with $match) to determine what to replace it with
        return 'replacement';
    }, $master_string);
    
    0 讨论(0)
  • 2021-01-23 06:29

    This is a situation that calls for preg_replace_callback:

    // Assume this already exists
    function mapSubstringToInteger($str) {
        return (strlen($str) % 4) + 1;
    }
    
    // So you can now write this:
    $pattern = '/%%abc%%(.*?)%%xyz%%/';
    $replacements = array('r1', 'r2', 'r3', 'r4');
    $callback = function($matches) use ($replacements) {
        return $replacements[mapSubstringToInteger($matches[1])];
    };
    
    preg_replace_callback($pattern, $callback, $input);
    
    0 讨论(0)
提交回复
热议问题