0

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

8
  • 1
    Avoid dealing with nested content using regex. Commented May 3, 2019 at 9:03
  • According to your template no substitution should occur as there is no value between dolor ( and ) sit in the original string Commented May 3, 2019 at 9:05
  • Yeah, it seems the example is wrong. Commented May 3, 2019 at 9:05
  • @thehennyy you're not obliged to escape the backets in a character class [] Commented May 3, 2019 at 9:06
  • Sorry for forgot escape special character in the sample. But it still not working even escaped the special character. Commented May 3, 2019 at 9:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.