[英]Php split string on different characters
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?谁能告诉我处理这个?
$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.这意味着
foo=bar<3
将无法被识别。 This can of course be changed to fit your needs:-).这当然可以根据您的需要进行更改:-)。
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)
.然后,您可以使用
count($result)
测试$result
中是否有任何内容(找到拆分字符)。
preg_match('/(\S)(=|==|!=|<|>|>=|<=)(\S)/', $subject, $matches)
Quick 'n dirty:快速'n脏:
$parts = preg_split('/[<>=!]+/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
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:)
希望能帮助到你:)
try:尝试:
$str = "address=test";
preg_match("/(?<k>.+?)(?<operator>[=|==|!=|<|>|>=|<=]{1,2})(?<v>.+?)/",$str,$match);
$match["k"] //addres
$match["operator"] //=
$match["v"] //test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.