Search code examples
phparraysstringexplodedelimited

Split words in string into an array without breaking phrases wrapped in double quotes


I want to let the user type in tags: windows linux "mac os x"

and then split them up by white space but also recognizing "mac os x" as a whole word.

Is this possible to combine the explode function with other functions for this?


Solution

  • As long as there can't be quotes within quotes (eg. "foo\"bar" isn't allowed), you can do this with a regular expression. Otherwise you need a full parser.

    This should do:

    function split_words($input) {
      $matches = array();
      if (preg_match_all('/("([^"]+)")|(\w+)/', $input, $reg)) {
        for ($ii=0,$cc=count($reg[0]); $ii < $cc; ++$ii) {
          $matches[] = $reg[2][$ii] ? $reg[2][$ii] : $reg[3][$ii];
        }
      }
      return $matches;
    }
    

    Usage:

    $input = 'windows linux "mac os x"';
    var_dump(split_words($input));