0

The text I am searching contains vars (= OR :) { (the stuff I want }

Between the = and the { can be only whitespace and may contain a new line.

I will be turning this into a key/value array in PHP.

Here is what I am attempting which does not result in any matches:

$str = "vars = {'first' : 'joe', 'last' : 'smith' };";

preg_match("/^vars\s=\s\{(.*)\}/",$str, $matches);

echo $matches[0];

another string that should match:

$str = "vars : {'first' : 'joe', 'last' : 'smith' };";

2 Answers 2

1

Maybe you could grab everything inside the { } and then let a JSON parser do the rest for you.

$str = 'vars = {"first" : "joe", "last" : "smith" };';
preg_match("/\{.*\}/",$str, $matches);
var_dump(json_decode($matches[0]));

object(stdClass)#1 (2) {
  ["first"]=>
  string(3) "joe"
  ["last"]=>
  string(5) "smith"
}

This approach only works with valid JSON ofc.

Sign up to request clarification or add additional context in comments.

2 Comments

You need to escape the {} and the () is unnecessary.
i changed the answer. ty.
0

To match it use:

preg_match_all('/^vars\s[=:]\s{(.*)};$/m', $str, $matches, PREG_PATTERN_ORDER);
$matches = $matches[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.