php - Regular expression to extract text between braces -
i trying extract text between curly braces in php. e.g
welcome {$user.first_name} {$site} version 1.5. username {$user.username}. reputation @ present {$user.reputation.name}
i have used \{\$(.*?)\} works fine in cases. matches:
- {$user.first_name}
- {$site}
- {$user.username}
- {$user.reputation.name}
but want match text has single or multiple . (dot) within braces. i.e above string should able match only:
- {$user.first_name}
- {$user.username}
- {$user.reputation.name}
please me achieve this! in advance.
you can use
\{\$([^.{}]+(?:\.[^.{}]+)+)\} see regex demo
note instead of lazy dot matching .*?, using negated character class [^.{}] matches character other ., { or }. thus, match block not contain ., , still within braces.
the regex breakdown:
\{\$- literal{$([^.{}]+(?:\.[^.{}]+)+)- group 1 matching[^.{}]+- 1 or more characters other.,{, or}(?:\.[^.{}]+)+- 1 or more (due+) sequences of\.- literal dot[^.{}]+- 1 or more characters other.,{, or}
\}- literal}
$re = '/\{\$([^.{}]+(?:\.[^.{}]+)+)\}/'; $str = "welcome {\$user.first_name} {\$site} version 1.5. username {\$user.username}. reputation @ present {\$user.reputation.name}"; preg_match_all($re, $str, $matches); print_r($matches[1]);
Comments
Post a Comment