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 }

ideone demo:

$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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -