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";`
Provided you simply want a string & underscores, and nothing else, in between the ___
's, then;
/___([a-zA-Z_]*)___/m
Edit
To fix the false positive on ______
, I've added a positive lookahead, and made a couple of other tweaks.
/_{3}(?=.*[a-zA-Z_])(.*[a-zA-Z_])_{3}/m
_{3}
- Matches 3 underscores
(?=.*[a-zA-Z_])
- Positive lookahead to make sure one of these characters is present
(.*[a-zA-Z_])
- The actual matching group
_{3}
- And match the ending 3 underscores
Try this using preg_replace_callback()
:
$string = "This string contains ___MY_VALUE___ which I want to replace and there is also ___ONE_MORE_VALUE___ which I want to replace";
$replaced = preg_replace_callback("/\___([a-zA-Z_]*)\___/", function($m){
return "(replaced {$m[1]})";
}, $string);
print_r($replaced);
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";
To replace everything that is not 3 underscores in between two "3 underscores", use this regex:
/___((?:(?!___).)+)___/
To replace "keywords" with corresponding values, use preg_replace_callback like that:
$replace = array(
'MY_VALUE' => '**Replacement of MY_VALUE**',
'ONE_MORE_VALUE' => '**Replacement of ONE_MORE_VALUE**',
' third value to be replaced ' => '**Replacement of third value to be replaced**',
);
$string = "This string contains ___MY_VALUE___ which I want to replace
and there is also ___ONE_MORE_VALUE___ which I want to replace.
This is the ___ third value to be replaced ___";
$string = preg_replace_callback('/___((?:(?!___).)+)___/',
function ($m) use($replace){
return $replace[$m[1]];
}
, $string);
echo $string,"\n";
Output:
This string contains **Replacement of MY_VALUE** which I want to replace
and there is also **Replacement of ONE_MORE_VALUE** which I want to replace.
This is the **Replacement of third value to be replaced**