I have string which contains a variable in curly braces and I want to replace them with a value.
$text = 'Hi My Name is ##{Name}## and I am ##{Adjective}##';
preg_match_all('/{([^#]+)}/i', $text, $matches);
foreach ($matches[1] as $key => $value) {
$text = str_replace('{' . $value . '}', 'SomeValue', $text);
}
print_r($matches[1]);
print_r(str_replace('##', '', $text));
OUTPUT
Array ( [0] => Name [1] => Adjective )
Hi My Name is SomeValue and I am SomeValue
But I am not able to handle deifferent variations of the string for example.
1. $text = 'Hi My Name is ##{Name}{Adjective}##'
2. $text = 'Hi My Name is ##{Name}and I am{Adjective}##'
3. $text = 'Hi My Name is ##{Name}, {Adjective}##'
4. $text = 'Hi My Name is ##{Name} {Adjective}##'
I would want the similar result in array output so that values can be replaced
Array ( [0] => Name [1] => Adjective )
NOTE: I am able to ensure that '##' will always be present at the start and end of the curly braces, but not necessarily in between the braces e.g. point 1,2,3,4 above in example string.
I'd recommend using preg_replace_callback
with the pattern /\{(.+?)}/
and a callback like this
$callback = function($matches) use (&$found) {
$found[] = $matches[1];
return 'SomeValue';
};
This will let you record the matches in the $found
array while replacing the entire {Name}
, {Adjective}
with "SomeValue".
$found = [];
$newTxt = str_replace('##', '',
preg_replace_callback('/\{(.+?)}/', $callback, $txt));
Demo here ~ https://eval.in/641827
Based on your question, you could first extract all the stuff that are between ## ##
, parse it, then replace it afterwards.
$text1 = 'Hi My Name is ##{Name}{Adjective}##';
$text2 = 'Hi My Name is ##{Name}and I am{Adjective}##';
$text3 = 'Hi My Name is ##{Name}, {Adjective}##';
$text4 = 'Hi My Name is ##{Name} {Adjective}##';
$the_text = $text2;
#get the stuff that's between ## ##
preg_match_all("/##.*?##/", $the_text, $matches);
foreach ($matches[0] as $match)
{
# you will have to change this a bit as you have name and adjectives
# but what this does is replace all the '{}' with 'somevalue'
$replace_this = preg_replace("/\{.*?\}/", "somevalue", $match);
# replaces the original matched part with the replaced part (into the original text)
$the_text = str_replace($match, $replace_this, $the_text);
}
echo $the_text . "<br>";