Question

I'd like to match and extract variables from: {{variable:int}}

  • variable would be anything a-z
  • : is a separator
  • int would be an integer 0-9

Curretly i have: preg_replace('!\{\{(\S+)\}\}!', "$1", $string) which does only half the job, i still have to split by :.

Thank you!

Was it helpful?

Solution

If you want to extract the name/value, I think you want to use preg_match.

preg_match('!\{\{(.*?):(\d)\}\}!', $string, $matches);  
$varname = $matches[1];  
$val = $matches[2];  

OTHER TIPS

You need a non-greedy match (.*?): preg_replace('!\{\{(.*?):(\d)\}\}!')

Use

{{([a-zA-Z]+):(\d+)}}

$1 will contain the captured variable, $2 will contain the captured integer

Explanation

{{([a-zA-Z])+:(\d+)}}

[a-zA-Z]+ means atleast one more alphabets (small or caps)
followed by a ":"
followed by atleast one or more digits (0-9)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top