I want to find substring in a string with ___string_string___ pattern where string_string can be any string.
$string = "This string contains ___MY_VALUE___ which I want to replace and there is also ___ONE_MORE_VALUE___ which I want to replace";`
I want to find substring in a string with ___string_string___ pattern where string_string can be any string.
$string = "This string contains ___MY_VALUE___ which I want to replace and there is also ___ONE_MORE_VALUE___ which I want to replace";`
The solution using preg_replace_callback with specific regex pattern:
// custom replacement list
$pairs = ['___MY_VALUE___' => 123, '___ONE_MORE_VALUE___' => 456];
$str = '"This string contains ___MY_VALUE___ which I want to replace and there is also ___ONE_MORE_VALUE___ which I want to replace";';
$str = preg_replace_callback('/___(([a-z]+_?)+)___/mi', function($m) use($pairs){
return (isset($pairs[$m[0]]))? $pairs[$m[0]] : $m[0];
}, $str);
print_r($str);
The output:
"This string contains 123 which I want to replace and there is also 456 which I want to replace";