Search code examples
phpexplodevar-dump

How not to explode sub-delimiter inside delimeter?


I have this string:

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

I need this var_dump() output with explode "(":

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

Solution

  • You can use php function preg_replace() with regex pattern to remove the text you don't want to be presented in output and after that use the explode function :

    $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));
    

    Result :

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

    Hope this will help.