Mission
Mission

Reputation: 1297

preg_replace problem

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

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

Thank you!

Upvotes: 1

Views: 153

Answers (3)

soulmerge
soulmerge

Reputation: 75704

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

Upvotes: 2

lyricat
lyricat

Reputation: 1996

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];  

Upvotes: 1

Jaskirat
Jaskirat

Reputation: 1094

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)

Upvotes: 1

Related Questions