Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explode string into tokens keeping quoted substr intact

Tags:

regex

php

I dont know where I seen it, but can anyone tell me how to accomplish this using php and regex?

'this is a string "that has quoted text" inside.'

i want to be able to explode it like this

[0]this
[1]is
[2]a
[3]string
[4]"that has quoted text"
[5]inside

keeping the quotes intact.

like image 738
madphp Avatar asked Mar 29 '11 15:03

madphp


2 Answers

Can you please try following code:

$str = 'this is a string  "that has quoted text" inside.';
var_dump ( preg_split('#\s*("[^"]*")\s*|\s+#', $str, -1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) );

Output: 
array(6) {
  [0]=>
  string(4) "this"
  [1]=>
  string(2) "is"
  [2]=>
  string(1) "a"
  [3]=>
  string(6) "string"
  [4]=>
  string(22) ""that has quoted text""
  [5]=>
  string(7) "inside."
}

Here is the link for above working code on dialpad

Update: For escaping support please try:

preg_split('#\s*((?<!\\\\)"[^"]*")\s*|\s+#', $str, -1 , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
like image 104
anubhava Avatar answered Oct 18 '22 20:10

anubhava


Requires PHP >= 5.3.0

$str = 'this is a string "that has quoted text" inside';

$x = str_getcsv($str,' ','"');

var_dump($x);

This strips the quotes, but does leave the content of the quoted block intact.

like image 24
Mark Baker Avatar answered Oct 18 '22 21:10

Mark Baker