PHP将字符串拆分为两个数组-值拆分和定界符

问题描述 投票:0回答:3

我想最有可能使用explode或preg_split拆分字符串以创建两个数组。首先是拆分的内容。秒是定界符。仅有的两个定界符将是“ AND”或“ OR”。

例如:

$ string =“名称= John AND St​​ate = GA OR State = CA”;

我不仅要捕获'Name = John,State = GA,State = CA',而且还要捕获它们之间的分隔符。

对于此示例,两个单独的数组将是:

array (
        [0] => Name=John
        [1] => State=GA
        [2] => State=CA   
)

array (
        [0] => AND
        [1] => OR
)

从这里我可以对数据进行按摩以使其符合我的要求,最后建立一个查询。如果有更好的解决方案,我会全力以赴。感谢您提供的所有帮助!

php explode preg-split
3个回答
1
投票

使用PHP Regular Expression。您所用的preg_match_all()功能:

Live Demo

代码:

$input = "Name=John AND State=GA OR State=CA";

preg_match_all("/[a-zA-Z]+\s*=\s*[a-zA-Z]+/", $input, $output_1);
$output_1 = $output_1[0];


preg_match_all("/AND|OR/", $input, $output_2);
$output_2 = $output_2[0];

print_r($output_1);
print_r($output_2);

输出:

Array
(
    [0] => Name=John
    [1] => State=GA
    [2] => State=CA
)
Array
(
    [0] => AND
    [1] => OR
)

0
投票

如果该字符串中的其他所有字符都是定界符(AND | OR),则无需使用正则表达式。用空格字符将该字符串分解为数组,然后将其他所有项都拾取到一个数组中,将其他项都拾取到另一个数组中。像这样:

<?php
$string = "Name=John AND State=GA OR State=CA";
$a = explode(' ', $string);

$foo = array();
$bar = array();
$len = count($a);

for($i = 0; $i < $len; $i++) {
    if($i % 2 === 0) {
        $foo[] = $a[$i];
    }
    else {
        $bar[] = $a[$i];
    }
}

print_r($foo);
print_r($bar);

https://eval.in/87538

并且如果该字符串中始终有相同数量的项目,则无需遍历它,只需将项目0、2和4分配给一个数组,将项目1和3分配给另一个数组。


0
投票

state值非常现实的可能性是俄勒冈OR),这意味着@rullof的答案不可靠。

通过在输入字符串的一次传递中使用值,可以稳定任务。

可以通过array_column()提取两个组。

代码:(Demo

$string = "Name=John AND State=OR OR State=CA";

if (preg_match_all(
        '~([a-zA-Z]+=\S+)(?: ([A-Z]{2,3}))?~',
        $string,
        $out,
        PREG_SET_ORDER
    )
) {
    echo "data = ";
    var_export(array_column($out, 1));
    echo "\nconjunctions = ";
    var_export(array_column($out, 2));
}

输出:

data = array (
  0 => 'Name=John',
  1 => 'State=OR',
  2 => 'State=CA',
)
conjunctions = array (
  0 => 'AND',
  1 => 'OR',
)
© www.soinside.com 2019 - 2024. All rights reserved.