0

Take this string:

$string = "wanted NOT IN OR"

preg_match_all('/\w+/', $string, $WordArray);
//  outputs each word into array

But what if I do not want to split on the whitespace right after the word "NOT".
Keeping the word "NOT" and the following word together, and then keep splitting as usual.

The array should end up looking like this:

$WordArray = [
    'wanted',
    'NOT IN',
    'OR'
'];

Did try with something like this, but.. yeah. That did not split as expected...

$WordArray = preg_split('/\s|\bNOT\s/');
ThomasK
  • 2,210
  • 3
  • 26
  • 35
  • What are the possible values of `$string`? – nice_dev Feb 16 '23 at 11:22
  • could be a lot. But the first word would always be a database fieldname (which could be just about any word. Next could be `IN | BETWEEN | LIKE | AND | OR`, and sometimes with `NOT` i front of one or more of these words... – ThomasK Feb 16 '23 at 11:33
  • 1
    How about this regex `/NOT\s\w+|\w+/`? – tobifasc Feb 16 '23 at 11:51
  • So something like this? https://3v4l.org/4Q6fi – nice_dev Feb 16 '23 at 12:47
  • Yes. The first regex seems to do the trick. Thanks. I couldn't figure out how to use the | part in this.. – ThomasK Feb 16 '23 at 14:40
  • [Regular expression to match common SQL syntax?](https://stackoverflow.com/q/139926/2943403) When you ask for a regex solution, but offer very limited sample data, the reliability of our advice will not be awesome. – mickmackusa Feb 17 '23 at 05:32
  • Im sorry. But yes. The regex was for a shorthand string for the where clause. And the complete string is in fact `wanted NOT IN OR` where the first word is fieldname, and the second could be one of the keywords i mentioned, and at last the `OR` is if I need to change the default AND to `OR`.. – ThomasK Feb 17 '23 at 21:14

0 Answers0