Regular Expressions 101

Community Patterns

Community Library Entry

1

Regular Expression
PCRE (PHP <7.3)

/
(\[(?:[^[\]]*?)\]\s*?(?=\[))|(\[(?:[^[\]]*?)\](?!\s*[\|&]\s*.))|(?:\[[^[\]]*?])|([^&\|\s]+)\s+(?=[^&\|\s]+)
/
g

Description

/**

  • this regex should match most cases where the user forgets to put an operator somewhere and add an OR, it still
  • does not handle nested square brackets but those are invalid anyways
  • this page has an explanation https://regex101.com/r/fF7wO1/2
  • the way this regex grabs conflicting matches is by oring different cases together in the order we want to grab them in
  • the first case is for a set of brackets immediately followed by an opening bracket (seperate them with an or)
  • the second case is for a set of brackets immediately followed by any non operator character (seperate with an or)
  • the third case is for a set of brackets followed by an operator (do nothing)
  • the final case is for two words outside of brackets seperated by a space (fill space with an or)
  • @type {RegExp} */
Submitted by warnock - 9 years ago