Get a string between the first parentisis that opens and the last one that closes

0

I need to get a string between the first parentisis that opens and the last one that closes, to then make a str_replace between those parentheses, finally perform an explode to get the fields.

Something like this:

$string = field1,field2,(if(isnull(table.id_),1,table.id_)) as field3,field4;

The function to call has to get this part of the code. (if (isnull (table.id _), 1, table.id_)) then:

$string_btwn_parenthesis = [(if(isnull(table.id_),1,table.id_))]; <- obtained by function

I want to get this - > (if (isnull (table.id _), 1, table.id _)) < - no - > (if (isnull (table.id _) < -, 1, table.id _))

$string_replaced = str_replace($string_btwn_parenthesis," ",$string);

$arrayfields = explode(",",$string_replaced);
    
asked by Rwa 21.03.2018 в 16:57
source

2 answers

0

What you need is to use regular expressions . Assuming I've understood your question well:

$test = "[(if(isnull(table.id_),1,table.id_))];";
$matches = [];
$values = preg_match('/(?<=\()(.+)(?=\))/is', $test, $matches);
$result = explode(',', $matches[1]);

What will produce a result like:

Array
(
    [0] => if(isnull(table.id_)
    [1] => 1
    [2] => table.id_)
)
    
answered by 21.03.2018 в 20:08
0

Try the following regular expression:

^[^\(]+|[^\)]+$|([a-zA-Z]\w*+(?:[.][a-zA-Z]\w*+)?)(?!\s*['"(])

Demo .

You should capture the columns that are inside the group of parentheses more external.

The regular expression will save the columns in the capture group 1. You have to check that this group has content, and if it does, it will turn out to be a column and you already do what you want with it.

Here you have an example printing the columns

<?php

$string = "field1,field2,(if(isnull(table.id_),1,table.id_)) as field3,field4;";

preg_match_all(
   "/^[^\(]+|[^\)]+$|([a-zA-Z]\w*+(?:[.][a-zA-Z]\w*+)?)(?!\s*['\"(])/"
  ,$string
  ,$matches
 );

$i = 0;
foreach ($matches[1] as $match) {
  if (!empty($match)) {
    print($matches[0][$i]) . "\n";
  }
  $i++;
}
    
answered by 03.08.2018 в 15:13