如何不在定界符内分解子定界符?

How not to explode sub-delimiter inside delimeter?

我有这个字符串:

text example (some text) (usb, apple (fruit), computer (technology), nature: sky)

我需要这个 var_dump() 输出 explode "(":

array(3) {
  [0]=>
  string(34) "text example"
  [1]=>
  string(12) "some text"
  [2]=>
  string(12) "usb, apple, computer, nature: sky"
}

您可以使用 php 函数 preg_replace() 和正则表达式模式来删除您不想在输出中显示的文本,然后使用 explode 函数:

$string = 'text example (some text) (usb, apple (fruit), computer (technology), nature: sky)';

//Remove (fruit) and (technology) from string 
$newString = preg_replace('/ \((\w+)\)/i', ', ', $string);

//Explode with new string
$output = explode(" (",$newString);

//Remove ')' from output
var_dump(preg_replace('/\)/i', '', $output));

结果:

array(3) { 
  [0]=> string(12) "text example" 
  [1]=> string(9) "some text" 
  [2]=> string(35) "usb, apple, computer, nature: sky" 
}

希望这会有所帮助。