Home > Mobile >  Use a RegEx in PHP to find and save multiple occurences in a string
Use a RegEx in PHP to find and save multiple occurences in a string

Time:04-19

I got this string:

if(conditionA==valueA-AND-conditionB==valueB-OR-conditionC==valueC)

The String can contain indefinite occurences of conditions.

and I want an array that contains:

array(3) {
  [0]=>
  string(...) "conditionA==valueA"
  [1]=>
  string(...) "conditionB==valueB"
  [2]=>
  string(...) "conditionC==valueC"
}

I am currently using this pattern:

preg_match("/^if\((. )-(. )\)/U", $current_step_data_exploded[0], $if_statements);

Also, I need the "ANDs" and "ORs" so I can further check the statements. My RegEex doesn't deliver. Can somebody help me?

CodePudding user response:

$string = "if(conditionA==valueA-AND-conditionB==valueB-OR-conditionC==valueC)";
$match = preg_match('/^if\((. )\)$/', $string, $if);
if ($match) {
  $conditions = preg_split('/\-(AND|OR)\-/', $if[1], -1, PREG_SPLIT_DELIM_CAPTURE);
  print_r($conditions);
} else {
  echo "no matches.";
}

will output:

Array
(
    [0] => conditionA==valueA
    [1] => AND
    [2] => conditionB==valueB
    [3] => OR
    [4] => conditionC==valueC
)

CodePudding user response:

You could make use of the \G anchor and a capture group:

(?:\bif\((?=[^()]*\))|\G(?!^))(.*?==.*?)(?:-(?:AND|OR)-|\)$)

Explanation

  • (?: Non capture group
    • \bif\((?=[^()]*\) Match if( and assert a closing )
    • | Or
    • \G(?!^) Assert the current position at the end of the previous match, not at the start
  • ) Close the non capture group
  • (.*?==.*?)
  • (?:-(?:AND|OR)-|\)$) Match one of -AND- -OR-or)` and the end of the string

Regex demo | PHP demo

Example

$re = '/(?:\bif\((?=[^()]*\))|\G(?!^))(.*?==.*?)(?:-(?:AND|OR)-|\)$)/';
$str = 'if(conditionA==valueA-AND-conditionB==valueB-OR-conditionC==valueC)';

preg_match_all($re, $str, $matches);
print_r($matches[1]);

Output

Array
(
    [0] => conditionA==valueA
    [1] => conditionB==valueB
    [2] => conditionC==valueC
)
  • Related