Home > Backend Development > PHP Tutorial > 拆分为数组,难点是 C(x, y("z", 2, 0)), 是一个整体。

拆分为数组,难点是 C(x, y("z", 2, 0)), 是一个整体。

WBOY
Release: 2016-06-23 13:33:41
Original
596 people have browsed it


将字符串 $s='A, B, C(x, y("z", 2, 0)), D, E';
拆分为数组,难点是 C(x, y("z", 2, 0)), 是一个整体。

想要的结果:
array(
  'A', 
  'B', 
  'C(x, y("z", 2, 0))', 
  'D',
  'E');


回复讨论(解决方案)

$s='A, B, C(x, y("z", 2, 0)), D, E';$keywords = preg_split("/\,\s(?=[A-Z])/", $s);var_dump($keywords);
Copy after login
Copy after login

$s='A, B, C(x, y("z", 2, 0)), D, E';$keywords = preg_split("/\,\s(?=[A-Z])/", $s);var_dump($keywords);
Copy after login
Copy after login



-----------------------------
非常感谢你的回复!但是靠?=[A-Z] 不准确,因为有可能括号内也是大写(嵌套的括号内不管什么内容是一个整体)。
$s='A, B, C(X, Y("Z", 2, 0)), D, E';

$s='A, B, C(X, Y("Z", 1, 0)), D(X, Y("Z", 2, 0)), E,F(X, Y("Z", 3, 0))';//提取获取里面的内容preg_match_all("/\(.*?\)\)/",$s,$match);//这部分正则可以自行修改$s = str_replace($match[0],'%',$s);//将整体的替换成某个符合,%百分号也可以自己选定$exs = explode(',',$s);$i = 0;foreach($exs as $key=>$value){	if (strpos($value,"%") !== false) {				$exs[$key] = str_replace('%',$match[0][$i],$value);		$i ++;	}}var_dump($exs);
Copy after login

帮你在复杂化了

所以这种事情不是正则能够胜任的,老老实实写个函数比绞尽脑汁写正则实惠的多

$s='A, B, C(x, Y("z", 2, 0)), D, E';print_r(foo($s));function foo($s) {  $r = array();  $m = 0;  $t = '';  for($i=0; $i<strlen($s); $i++) {    if($s{$i} == '(') $m++;    if($s{$i} == ')') $m--;    if($m == 0 && $s{$i} == ',') {      if($t) $r[] = $t;      $t = '';    }else $t .= $s{$i};  }  if($t) $r[] = $t;  return $r;}
Copy after login
Array(    [0] => A    [1] =>  B    [2] =>  C(x, Y("z", 2, 0))    [3] =>  D    [4] =>  E)
Copy after login

感谢2位的回复。
想到了一个匹配括号嵌套的正则,有类似计算的可以参考一下。(没有严谨测试)

$s='A, B,C(X, Y("Ez", 2, 0, Z(kk, 99))),D, E(u(8 , D(88)))';
preg_match_all('/[A-Z](?=[,])|[^,]*\(([^()]+|(?R))*\)/',$s,$z);
print_r($z[0]);

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template