William Buttlicker
William Buttlicker

Reputation: 6000

Find a pattern in string

I have a string like this:

{param1}{param2}{param3}....{myparam paramvalue}{paramn}

How can i get the paramvalue of myparam

Upvotes: 0

Views: 940

Answers (5)

NeverHopeless
NeverHopeless

Reputation: 11233

You can try this one as well:

.+?\s+([^}]+)

EDIT

Explanation:

.+?     means match everything one or more time but its lazy, will prefer to match as less as it can. 
\s+     means it will match white-spaces one or more time. 
([^}]+) means match everything except `}`(close bracket) one or more time and capture group.

Upvotes: 0

Robert
Robert

Reputation: 20286

Simple regex:

/\({[^ ]+?) ([^}]+?)\}/
  • {[^ ]+?) - it will look for anything at least 1 time occured but space and put it in subpattern
  • ([^}]+?) - it will look for anything at least 1 time occured but { and put it in subpattern.

use it with preg_match() function

OR

The other simple regex:

preg_match('/([a-z0-9]+?) ([a-z0-9]+?)\}/', $str, $matches);
  • ([a-z0-9]+?) - a-z 0-9 at least one time not greedy
  • ([^}]+?) - a-z 0-9 at least one time not greedy

Output:

Array ( [0] => myparam paramvalue} [1] => myparam [2] => paramvalue )

Demo

Upvotes: 2

Ja͢ck
Ja͢ck

Reputation: 173562

To specifically get that parameter value, you first have to match the left part:

/\{myparam/

Followed by at least one space:

/\{myparam\s+/

Capture characters until a closing curly brace is found:

/\{myparam\s+([^}]+)\}/

The expression [^}]+ is a negative character set, indicated by the ^ just after the opening bracket; it means "match all characters except these".

Upvotes: 1

Thomas L.
Thomas L.

Reputation: 104

if(preg_match('/\{'.preg_quote('myparam').' ([^\}]+)\}/', $input, $matches) {
  echo "myparam=".$matches[1];
} else {
  echo "myparam not found";
}
  1. in preg_match, '{' and '}' are special chars, so they need to be escaped
  2. the preg_quote may not be neccessary, as long as "myparam" will never have any special regex chars
  3. the (cryptic) part ([^}]+)} matches one or more chars not being a '}', followed by '}'
  4. the parantheses make that match available in the third arg to preg_match, $matches in this case

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

Try with this regex:

/\{\w+\s+(\w+)\}/

Upvotes: 1

Related Questions