Created
April 4, 2025 13:42
-
-
Save styledev/d83c74f612e7529f0e472919dc818b2f to your computer and use it in GitHub Desktop.
Regex Lazy Operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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