Trouble parsing a delimited string in php
I'm extracting values from a delimited string that usually has the form:
valueA|valueB|valueC
Where '|' is a delimiter.
In this simple case, I'm just using explode to extract the separate values. However, sometimes the string will have brackets, where any characters including '|' can be b开发者_如何学运维etween those brackets. For example:
valueA|valueB[any characters including '|']|valueC
How can I parse this string to reliably extract the three separate values (valueA, valueB[any characters including '|'], valueC). I'm pretty sure a regex is my best bet, but I haven't been able to figure it out.
Any help is appreciated. Thanks!
Per the comments to the question, you have the ability to change the format. That being the case, one small adjustment will have you rolling. Since it's character-delimited, you're essentially working with a CSV file. Conventionally, CSV functionality allows you to enclose the data values in quotes between the delimiters. That way, if your delimiter character occurs within a piece of data, it will be parsed simply as part of the data string and not mistaken for a delimiter.
That's how spreadsheets work -- the delimiter is usually a comma or tab, but fields can still have commas/tabs in them because they're enclosed in quotes. Those quotes are part of the standard CSV format, and PHP's CSV functions recognize them.
As a simple illustration, your old strings:
valueA|valueB|valueC
valueA|valueB[any characters including '|']|valueC
would then be this:
"valueA"|"valueB"|"valueC"
"valueA"|"valueB[any characters including '|']"|"valueC"
See how the StackOverflow syntax highlighter catches that above? :-)
There are PHP functions for both reading and writing CSV formats like this.
Writing CSV from an array of fields: fputcsv()
(to a file descriptor)
Reading CSV into an array: fgetcsv()
(from a file) or str_getcsv()
(from a string, new in 5.3)
Default assumes that the delimiter is a comma and enclosure is a double quote, but you can optionally specify any character (such as '|') for those tasks.
精彩评论