2

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 within the master string. Each of these occurrences need to be replaced with a string from within an array array('substring1','substring2','substring3','substring4') depending upon the response of a function() which returns back a integer between 1 to 4.

I am not able to figure out an efficient way to do this.

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Note that $pattern is a regex string, so if you change $pattern make sure you escape any regex characters
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.