Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 595
Bert Avatar asked Oct 28 '25 04:10

Bert


1 Answers

$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 :-).

like image 168
yankee Avatar answered Oct 30 '25 18:10

yankee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!