I am using the preg_split function in PHP in order to create one array containing several different elements. However, I want to exclude a string which happens to contain one of the elements that I’m preg_splitting by.
$array['stuff'] = preg_split('/\[#]|\ & |\ & |\& |\&|\ &|\ > |\ > |\> |\>|\ >|\ & |\ & |\& |\&|\ &|\ \/ |\ \/ |\\/ |\\/|\ \/|\ > |\ > |\> |\>|\ >|\ , |\ , |\, |\,|\, |\ :: |\ :: |\:: |\ ::|\::|\ ::|\ : |\ : |\: |\:|\ :|\ - |\ - |\- |\-|\ -/', $array['stuff'] ) ;
What I would like to do is to exclude a string such as ‘foo-bar’ from being matched for a split because it contains a dash. ‘foo-bar’ would need to be an exact match for my purposes.
The resulting regular expression would be very complicated specially if you have a lot exceptions like ‘foo-bar’.
You should use a conditional subpattern with a lookbehind as condition and a lookahead as its yes-pattern:
result:
Let me explain what is happening here.
\-meansbut what we want is
Since we can’t implement that in regex as it is we change it a little:
To implement the if part we use a conditional subpattern, this is the syntax:
Our “condition” would be “preceded by foo” to check for that we use a lookbehind:
If that is true we should look for “a dash that is not followed by bar” to do that we use a negative lookahead:
And that becomes our “yes-pattern”. Our “no-pattern” should be
\-or “any dash”. The complete regex would be:UPDATE: to incorporate this into your current regex change this part at the end:
to