orion10
orion10

Reputation: 33

Trying to create a regex in PHP that matches patterns inside a pattern

I have seen some regex examples where the string is "Test string: Group1Group2", and using preg_match_all(), matching for patterns of text that exists inside the tags.

However, what I am trying to do is a bit different, where my string is something like this:

"some t3xt../s8fo=123,sij(variable1=123,variable2=743,variable3=535)"

What I want to do is match the sections such as 'variable=123' that exist inside the parenthesis.

What I have so far is this:

if( preg_match_all("/\(([^\)]*?)\)"), $string_value, $matches )
{
   print_r( $matches[1] );
}

But this just captures everything that's inside the parenthesis, and doesn't match anything else.

Edit: The desired output would be:

   "variable1=123"
   "variable2=743"
   "variable3=535"

The output that I am getting is:

   "variable1=123,variable2=743,variable3=535"

Upvotes: 3

Views: 70

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You can extract the matches you need with a single call to preg_match_all if the matches do not contain (, ) or ,:

$s = '"some t3xt../s8fo=123,sij(variable1=123,variable2=743,variable3=535)"';
if (preg_match_all('~(?:\G(?!\A),|\()\K[^,]+(?=[^()]*\))~', $s, $matches)) {
    print_r($matches[0]);
}

See the regex demo and a PHP demo.

Details:

  • (?:\G(?!\A),|\() - either end of the preceding successful match and a comma, or a ( char
  • \K - match reset operator that discards all text matched so far from the current overall match memory buffer
  • [^,]+ - one or more chars other than a comma (use [^,]* if you expect empty matches, too)
  • (?=[^()]*\)) - a positive lookahead that requires zero or more chars other than ( and ) and then a ) immediately to the right of the current location.

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 78994

I would do this:

preg_match("/\(([^\)]+)\)/", $string_value, $matches);
$result = explode(",", $matches[1]);

If your end result is an array of key => value then you can transform it into a query string:

preg_match("/\(([^\)]+)\)/", $string_value, $matches);
parse_str(str_replace(',', '&', $matches[1]), $result);

Which yields:

Array
(
    [variable1] => 123
    [variable2] => 743
    [variable3] => 535
)

Or replace with a newline \n and use parse_ini_string().

Upvotes: 2

Related Questions