简体   繁体   中英

Get values from formatted, delimited string with quoted labels and values

I have an input string like this:

"Day":June 8-10-2012,"Location":US,"City":Newyork

I need to match 3 value substrings:

June 8-10-2012

US

Newyork

I don't need the labels.

Per my comment above, if this is JSON, you should definitely use those functions as they are more suited for this.

However, you can use the following REGEX.

/:([a-zA-Z0-9\\s-]*)/g

<?php
preg_match('/:([a-zA-Z0-9\s-]*)/', '"Day":June 8-10-2012,"Location":US,"City":Newyork', $matches);
print_r($matches);

The regex demo is here:

https://regex101.com/r/BbwVQ5/1

Here are a couple of simple ways:

Code: ( Demo )

$string = '"Day":June 8-10-2012,"Location":US,"City":Newyork';

var_export(preg_match_all('/:\K[^,]+/', $string, $out) ? $out[0] : 'fail');

echo "\n\n";

var_export(preg_split('/,?"[^"]+":/', $string, 0, PREG_SPLIT_NO_EMPTY));

Output:

array (
  0 => 'June 8-10-2012',
  1 => 'US',
  2 => 'Newyork',
)

array (
  0 => 'June 8-10-2012',
  1 => 'US',
  2 => 'Newyork',
)

Pattern #1 Demo \\K restarts the match after : so that a positive lookbehind can be avoided (saving "steps" / improving pattern efficiency) By matching all following characters that are not a comma, a capture group can be avoided (saving "steps" / improving pattern efficiency).

Patter #2 Demo ,? makes the comma optional and qualifies the leading double-quoted "key" to be matched (split on). The targeted substring to split on will match the full "key" substring and end on the following : colon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM