phpregexsplitconditional-statementstokenize

Split string representing a comparison condition into its three parts


I want to split a string on different characters and I want to know what the 'splitter' is.

The string can be for example:

"address=test"
"number>20"
"age<=55"

In these cases I want to get the name, the seperator and the value in an array.

array[0]='address';
array[1]='=';
array[2]='test';

The separators are =,==,!=,<,>,>=,<=.

Can anyone tell me to deal with this?


Solution

  • $strings = array("address=test","number>20","age<=55");
    foreach($strings as $s)
    {
      preg_match('/([^=!<>]+)(=|==|!=|<|>|>=|<=)([^=!<>]+)/', $s, $matches);
      echo 'Left: ',$matches[1],"\n";
      echo 'Seperator: ',$matches[2],"\n";
      echo 'Right: ',$matches[3],"\n\n";
    }
    

    Outputs:

    Left: address
    Seperator: =
    Right: test
    
    Left: number
    Seperator: >
    Right: 20
    
    Left: age
    Seperator: <=
    Right: 55
    

    Edit: This method using the [^=!<>] makes the method to prefer failing completely over giving unexpected results. Meaning that foo=bar<3 will fail to be recognized. This can of course be changed to fit your needs :-).