Hello.

For example, there is a text:

[ SIMPLE TRUTH [ DEMO VIEW ] ] 

It should output only [DEMO VIEW], since there is no word TRUTH inside the brackets. Help write this expression.

  • one
    . (?! [[^]] *? TRUSH [^]] *]) [[^]] *] - ReinRaus
  • Does not work. - Essle Jaxcate
  • Correct the typo (TRUSH on TRUTH) and work. - VenZell
  • Did not notice. Thanks It works. - Essle Jaxcate
  • But no. Even if there is the word TRU, then the regular example is for TRUTH - Essle Jaxcate

1 answer 1

Using regular expressions for the match of negative expressions is quite problematic, especially since you can have recursive options, brackets inside the brackets.

It is much easier to parse these brackets using a finite state machine and then simply check for the presence of the word TRUTH in the string.

Something like this:

 function prepareData($str, &$data, $offset = 0) { $l = strlen($str); $buf = ''; for ($i = $offset; $i < $l; $i++) { $char = $str[$i]; switch ($char) { case '[': $buf .= substr($str, $offset, $i - $offset); $offset = $i = prepareData($str, $data, $i + 1) + 1; break; case ']': $buf .= substr($str, $offset, $i - $offset); $data[] = $buf; return $i; break; } } } $str = '[ SIMPLE TRUTH [ DEMO VIEW ] [ ANOTHER DEMO ] DEMO ] [ THIRD DEMO ] '; $data = array(); prepareData($str, $data); print_r($data); foreach ($data as $line) { if (strpos($line, 'TRUTH') === false) { echo $line."\n"; } } 

The output will be as follows:

Array ( [0] => DEMO VIEW [1] => ANOTHER DEMO [2] => SIMPLE TRUTH DEMO [3] => THIRD DEMO ) DEMO VIEW ANOTHER DEMO THIRD DEMO

  • It is possible in more detail. Did not understand you. - Essle Jaxcate
  • supplemented the answer. - Alex Kapustin