Reputation:
I have string:{$value.level-1.level-2.level-3 ... level-n}
and i need to change it to {$value['level-1']['level-2']['level-3'] ... ['level-n']}
.
I now how to make only for one:
preg_replace('(\{\$(.*?)\.(.*?)\})', '{$$1[\'$2\']}', $string);
But how can i repeat it for all levels?
Upvotes: 2
Views: 245
Reputation: 44851
You don't need regex for this. For what you're trying to do, it's unnecessarily complicated, hard to read, and hard to maintain. Just use str_replace
instead:
$leadinString = '$value'; // or '$test' or 'foobar' or whatever
$str = '{$value.level-1.level-2.level-3 ... level-n}';
echo str_replace(array("$leadinString.", '}', '.'), array($leadinString . "['", "']", "']['"), $str);
Note: I edited this based on your comment.
Upvotes: 0
Reputation: 22845
Try this:
preg_replace('#\.([a-zA-Z0-9_-]+)#', '[\'$1\']', $string)
Upvotes: 1