Reputation: 434
I'm creating a templating system that can allow a user to create a template and use the selected/dynamic value from the original string.
Example:
Original string:
Lorem ipsum dolor (Hello world) sit YEAH amet
Template:
consectetur adipiscing elit, sed do @BETWEEN("dolor (",") sit") eiusmod tempor incididunt ut labore et dolore @BEWTEEN("sit","amet")
Output:
consectetur adipiscing elit, sed do Hello world eiusmod tempor incididunt ut labore et dolore YEAH
I'm trying to get the @BETWEEN from the template by using regex
@BETWEEN\([^\(\)]+\)
But it did not work due to the bracket symbol in the @BETWEEN bracket. I'm not very good at regex. Can anyone give me suggestion on how to enhance the regex or any other method to get the @BETWEEN function from the template
Upvotes: 0
Views: 231
Reputation: 147206
Since your template pattern looks for strings enclosed in quotes e.g. "dolor ("
, you can find those values, create a regex out of them to look for the matching string in your original string, and then use that match to replace the patterns in the template with the value from the original string.
$string = 'Lorem ipsum dolor (Hello world) sit YEAH amet';
$template = 'consectetur adipiscing elit, sed do @BETWEEN("dolor (",") sit") eiusmod tempor incididunt ut labore et dolore @BETWEEN("sit","amet")';
preg_match_all('/@BETWEEN\("([^"]+)","([^"]+)"\)/', $template, $matches, PREG_SET_ORDER);
foreach ($matches as $temp) {
$regex = '/' . preg_quote($temp[1]) . '(.*?)' . preg_quote($temp[2]) . '/';
preg_match($regex, $string, $replacement);
$template = preg_replace('/' . preg_quote($temp[0]) . '/', $replacement[1], $template);
}
echo $template;
Output:
consectetur adipiscing elit, sed do Hello world eiusmod tempor incididunt ut labore et dolore YEAH
Note that this will not work if the strings in your template patterns also contain escaped quotes. To implement this functionality in that case, you would need to use a regex derived from something like this question.
Upvotes: 1