Reputation: 454
I'm in the process of writing a theme based script and need a way to replace "variables" or tokens that weren't replaced by the script.
The format is:
^_variablename_^
So say, after processing the following, with variables: name=Adam, Occupation=programmer
Hello, my name is ^_title_^^_name_^, and I work as a ^_occupation_^.
We'd be left with ^_title_^
still in place.
I need a way to get rid of these, without knowing the name of the "variable".
Thanks in advance :)
Upvotes: 0
Views: 84
Reputation: 20753
Try using preg_replace_callback, when substitute variables in so you can simply ignore ones you can't substitute in:
$input = 'Hello, my name is ^_title_^^_name_^, and I work as a ^_occupation_^. ';
$variables = array('name' => 'adam');
$re = preg_replace_callback('/\^_(?<var>.+?)_\^/', function($params) use ($variables) {
if (isset($variables[$params['var']])) {
return $variables[$params['var']];
} else {
return '';
}
},
$input);
print $re;
This uses anonymous function syntax that works since php 5.3.0, you might need to declare a separate callback for this if you want to use it on earlier versions.
Upvotes: 0
Reputation: 5390
$str = 'Hello, my name is ^_title_^Adam, and I work as a programmer.';
echo preg_replace('/^_[\w_-]+_^/i', '', $str);
Upvotes: 0
Reputation: 39724
Process again:
$str = 'Hello, my name is ^_title_^Adam, and I work as a programmer.';
$str = preg_replace('/\^_(\w+)_\^/', '', $str);
echo $str;
Upvotes: 1