Skip to content

Instantly share code, notes, and snippets.

@styledev
Created April 4, 2025 13:42
Show Gist options
  • Save styledev/d83c74f612e7529f0e472919dc818b2f to your computer and use it in GitHub Desktop.
Save styledev/d83c74f612e7529f0e472919dc818b2f to your computer and use it in GitHub Desktop.
Regex Lazy Operator
<?php
/*
Trying to capture text that is wrapped in curly braces (e.g. {example})
Problem: [\S\ ]* would capture multiple tags that are on the same line.
*/
preg_match_all("(\{[\S\ ]*\})", $template, $tags);
// $tags = "{field=first_name} - {field=last_name}" ]
/*
Solution: Add a ? after the group quantifier to make it lazy and stop after the first occurence of the next character.
In our example [\S\ ]*\} we want to stop at the first ending curly brace.
*/
preg_match_all("(\{[\S\ ]*?\})", $template, $tags);
// $tags = ["{field=first_name}", "{field=last_name}"]
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment