Reputation: 855
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?
Upvotes: 4
Views: 692
Reputation: 17457
try:
$str = "address=test";
preg_match("/(?<k>.+?)(?<operator>[=|==|!=|<|>|>=|<=]{1,2})(?<v>.+?)/",$str,$match);
$match["k"] //addres
$match["operator"] //=
$match["v"] //test
Upvotes: 0
Reputation: 78006
Try this:
list($key, $splitter, $val) = split('[^a-z0-9]+', $str);
echo 'Key: '.$key.'; Splitter: '.$splitter.'; Val: '.$val;
This assumes that your keys and vals are alphanumeric. Hope it helps :)
Upvotes: 0
Reputation: 360862
Quick 'n dirty:
$parts = preg_split('/[<>=!]+/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
Upvotes: 1
Reputation: 40860
$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 :-).
Upvotes: 7
Reputation: 163593
Untested but should work:
$seps=array('=', '==', '!=', '<', '>', '>=', '<=');
$lines=array(
"address=test",
"number>20",
"age<=55"
);
foreach ($lines as $line) {
$result=array();
foreach ($seps as $sep) {
$offset=strpos($line, $sep);
if (!($offset===false)) {
$result[0]=substr($line, 0, $offset);
$result[1]=substr($line, $offset, 1);
$result[2]=substr($line, $offset+1);
}
}
print_r($result);
}
You can then test if $result
has anything in it (split character was found) by using count($result)
.
Upvotes: 0