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

WBOY
Release: 2016-06-13 12:21:00
Original
1049 people have browsed it

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

将字符串 $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';<br />$keywords = preg_split("/\,\s(?=[A-Z])/", $s);<br />var_dump($keywords);
Copy after login

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

帮你在复杂化了
------解决思路----------------------
所以这种事情不是正则能够胜任的,老老实实写个函数比绞尽脑汁写正则实惠的多
$s='A, B, C(x, Y("z", 2, 0)), D, E';<br />print_r(foo($s));<br /><br />function foo($s) {<br />  $r = array();<br />  $m = 0;<br />  $t = '';<br />  for($i=0; $i<strlen($s); $i++) {<br />    if($s{$i} == '(') $m++;<br />    if($s{$i} == ')') $m--;<br />    if($m == 0 && $s{$i} == ',') {<br />      if($t) $r[] = $t;<br />      $t = '';<br />    }else $t .= $s{$i};<br />  }<br />  if($t) $r[] = $t;<br />  return $r;<br />}
Copy after login
Array<br />(<br />    [0] => A<br />    [1] =>  B<br />    [2] =>  C(x, Y("z", 2, 0))<br />    [3] =>  D<br />    [4] =>  E<br />)<br /><br />
Copy after login

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