代码之家  ›  专栏  ›  技术社区  ›  kostya572

如何不分解delimeter内的子分隔符?

  •  0
  • kostya572  · 技术社区  · 11 年前

    我有这个字符串:

    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"
    }
    
    1 回复  |  直到 11 年前
        1
  •  0
  •   kostya572    11 年前

    您可以使用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" 
    }
    

    希望这会有所帮助。