解析 SQL SELECT 子句文本并创建一个包含每个列/表达式的数组

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

我有一个字符串如下:

$str = "am_customers.customer_key,am_customers.add_dt,CONCAT(am_customers.first_name,'',am_customers.last_name) as name,am_customers.cell_phone,am_customers.crm_phase_key,am_customers.source,am_customers.location_key,am_customers.hub_key,am_customers.crm_priority,am_customers.update_dt";

我想用逗号分解字符串。但问题在于左括号和右括号,当我尝试用逗号分解字符串时,我会得到如下结果

Array
(
    [0] => am_customers.customer_key
    [1] => am_customers.add_dt
    [2] => CONCAT(am_customers.first_name
    [3] => ''
    [4] => am_customers.last_name) as name
    [5] => am_customers.cell_phone
    [6] => am_customers.crm_phase_key
    [7] => am_customers.source
    [8] => am_customers.location_key
    [9] => am_customers.hub_key
    [10] => am_customers.crm_priority
    [11] => am_customers.update_dt
)

但我想要的结果如下:

Array
(
    [0] => am_customers.customer_key
    [1] => am_customers.add_dt
    [2] => CONCAT(am_customers.first_name,'',am_customers.last_name) as name
    [3] => am_customers.last_name) as name
    [4] => am_customers.cell_phone
    [5] => am_customers.crm_phase_key
    [6] => am_customers.source
    [7] => am_customers.location_key
    [8] => am_customers.hub_key
    [9] => am_customers.crm_priority
    [10] => am_customers.update_dt
)

有什么办法可以像我上面想要的那样吗?

php split text-parsing sql-parser
1个回答
1
投票

受到@Devon评论的启发,你可以通过

preg_match_all
来实现这一点:

preg_match_all( '/[^C\(,]*(?:(?:Cf\.|C(?!f)|\([^)]*\))[^C\(,]*)*/', $str, $matches );

正则表达式来源:http://www.perlmonks.org/?node_id=907316

我刚刚测试了这段代码,它似乎可以满足您的要求:

$str = "am_customers.customer_key,am_customers.add_dt,CONCAT(am_customers.first_name,'',am_customers.last_name) as 
             name,am_customers.cell_phone,am_customers.crm_phase_key,  am_customers.source,am_customers.location_key,am_customers.hub_key,
             am_customers.crm_priority,am_customers.update_dt";

$matches = [];
preg_match_all( '/[^C\(,]*(?:(?:Cf\.|C(?!f)|\([^)]*\))[^C\(,]*)*/', $str, $matches );

/*
* Trims each match, removes empty string matches, and resets array keys.
*
* Source: http://php.net/manual/en/function.array-filter.php#111091
*/
$clean = array_map( 'trim', $matches[0] );
$clean = array_filter( $clean, 'strlen' );
$clean = array_values( $clean );

var_dump( $clean );

文档

array_filter
http://php.net/array_filter

array_map
http://php.net/array_map

array_values
http://php.net/array_values

preg_match_all
http://php.net/preg_match_all

© www.soinside.com 2019 - 2024. All rights reserved.