How could I find all whitespaces excluding the ones between quotes?

前端 未结 5 1533
野性不改
野性不改 2020-12-10 06:48

I need to split string by spaces, but phrase in quotes should be preserved unsplitted. Example:

  word1 word2 \"this is a phrase\" word3 word4 \"this is a s         


        
5条回答
  •  感动是毒
    2020-12-10 07:07

    assuming your quotes are well defined, ie, in pairs, you can explode and go through for loop every 2 fields. eg

    $str = "word1 word2 \"this is a phrase\" word3 word4 \"this is a second phrase\" word5 word6 \"lastword\"";
    print $str ."\n";
    $s = explode('"',$str);
    for($i=1;$i

    output

    $ php test.php
    Spaces found: this is a phrase
    Spaces found: this is a second phrase
    

    No complicated regexp required.

提交回复
热议问题