2

I am having a string in PHP like this-

$str = "Foo var1='Abook' var2='A book'";

I am trying to convert this string to array that will treat the words inside the '' quotes as single statement (i.e they will ignore the spaces inside '' quotes). So my array will look like

Array
(
   [0] => "Foo",
   [1] => "var1='Abook'",
   [3] => "var2='A book'"
)

Note that the array is formed the seperating the string by the space outside '' quotes, But not inside it.

Can you please give me some good preg function so that I can accomplish this.

Ejzy
  • 400
  • 4
  • 13
ashutosh
  • 1,192
  • 5
  • 22
  • 46

4 Answers4

1

This will work for your sample input and output, but may not be general purpose enough for you. It's at least a starting point:

<?php
  $str = "Foo var1='Abook' var2='A book'";
  $res = array();

  $bits = explode(' ', $str, 2);

  $res[] = $bits[0];

  if (preg_match_all("/\w+='[^']+'/", $bits[1], $matches) !== false) {
    $res = array_merge($res, $matches[0]);
  }

  print_r($res);
?>
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
1

This solved my problem-

$str= 'word1 word2 \'this is a phrase\' word3 word4 "this is a second phrase" word5 word1 word2 "this is a phrase" word3 word4 "this is a second phrase" word5';

$regexp = '/\G(?:"[^"]*"|\'[^\']*\'|[^"\'\s]+)*\K\s+/';

$arr = preg_split($regexp, $str);

print_r($arr);

Original link Here. Obviously I needed only the correct regexp. Problem solved!!!

Community
  • 1
  • 1
ashutosh
  • 1,192
  • 5
  • 22
  • 46
0

here what you need:

$array = explode(' ', $str);

UPDATE

You can try this:

preg_match_all('/\'([^\']+)\'/', $string, $matches);
$matches = $matches[1];

Get all text between ' ' replace spaces to {SPACE} so your string would look like $str = "var1='A{SPACE}book'" then you can do explode() by spaces.

mmm?

rinchik
  • 2,642
  • 8
  • 29
  • 46
0
$s = "Foo var1='Abook' var2='A book'";
preg_match_all("~(?:(?<=^| )[^']+(?= |$)|(?<=^| )[^']+'[^']+'(?= |$))~", $s, $m);
print_r($m[0]);

Outputs:
Array
(
  [0] => Foo
  [1] => var1='Abook'
  [2] => var2='A book'
)
Aust
  • 11,552
  • 13
  • 44
  • 74