473,387 Members | 1,611 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

preg_match and delimited strings

I have a string I'd like to have broken into parts using preg_match. I
used a regular expression from the Perl FAQ (http://perlfaq.cpan.org/):
push(@new, $+) while $text =~ m{
"([^\"\\]*(?:\\.[^\"\\]*)*)",? # groups the phrase inside the
quotes
| ([^,]+),?
| ,
}gx;

The idea is that it splits delimited strings respecting the quotes, for
example...

foo, bar, "foo, bar", bar
would end up as
-foo
-bar
-"foo, bar"
-bar

So obviously an explode wont work.

I cant figure out how to convert that piece of perl above into
preg_match. I've copied the string and escaped all the appropriate
charecters however it still wont divide the string show above
properly...

$str = "foo, bar, \"foo, bar\", bar";
$re = "\"([^\\\"\\\\]*(?:\\\\.[^\\\"\\\\]*)*)\",?| ([^,]+),?| ,";
if (preg_match($re, $str, $res)) {
print_r($res);
}

I have other strings that need parsing too (including ones with a
double encapsulator inside the string - eg. 'don''t touch that!'). But
I'm saving those for later.

May 30 '06 #1
4 1804
Rik
si******@gmail.com wrote:
push(@new, $+) while $text =~ m{
"([^\"\\]*(?:\\.[^\"\\]*)*)",? # groups the phrase inside
the quotes
| ([^,]+),?
| ,
}gx;

I cant figure out how to convert that piece of perl above into
preg_match. I've copied the string and escaped all the appropriate
charecters however it still wont divide the string show above
properly...

$str = "foo, bar, \"foo, bar\", bar";
$re = "\"([^\\\"\\\\]*(?:\\\\.[^\\\"\\\\]*)*)\",?| ([^,]+),?| ,";
if (preg_match($re, $str, $res)) {
print_r($res);
}


It's a bitch for sure, isn't the wonderfull function fgetcsv() maybe
applicable in this case?

Grtz,
--
Rik Wasmus
May 31 '06 #2
Rik wrote:
si******@gmail.com wrote:
push(@new, $+) while $text =~ m{
"([^\"\\]*(?:\\.[^\"\\]*)*)",? # groups the phrase inside
the quotes
| ([^,]+),?
| ,
}gx;

I cant figure out how to convert that piece of perl above into
preg_match. I've copied the string and escaped all the appropriate
charecters however it still wont divide the string show above
properly...

$str = "foo, bar, \"foo, bar\", bar";
$re = "\"([^\\\"\\\\]*(?:\\\\.[^\\\"\\\\]*)*)\",?| ([^,]+),?| ,";
if (preg_match($re, $str, $res)) {
print_r($res);
}


It's a bitch for sure, isn't the wonderfull function fgetcsv() maybe
applicable in this case?

Grtz,
--
Rik Wasmus


Rik,

I'd have to write that part of the sql query out to a file and then
read it back in with fgetcsv(). However I do need to thank you, since
when I read through the page and the user contributed notes on the
fgetcsv() page I found a regex and a function that accomplished what I
needed...

function csv_string_to_array($str){
$expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
$results=preg_split($expr,trim($str));
return preg_replace("/^\"(.*)\"$/","$1",$results);
}

I just had to replace the \" with ' to get it to parse my strings. I
tested it with both '' and , in the encapsulated string and it works!

May 31 '06 #3
Rik
si******@gmail.com wrote:
I found a regex and a function that accomplished what I
needed...

function csv_string_to_array($str){
$expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
$results=preg_split($expr,trim($str));
return preg_replace("/^\"(.*)\"$/","$1",$results);
}
I just had to replace the \" with ' to get it to parse my strings. I
tested it with both '' and , in the encapsulated string and it works!

I hate to be the bearer of bad tidings, but it will fail on single escaped
\":

$str = '"baz,\"bax", bay, foz, "a, b", "foo';
$expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
$results=preg_split($expr,trim($str));
$res = preg_replace("/^\"(.*)\"$/","$1",$results);
print_r($res);

Array
(
[0] => "baz
[1] => \"bax"
[2] => bay
[3] => foz
[4] => "a, b"
[5] => foo
)

Properly nested, it can handle it:
$str = '"baz,\"bax\"", bay, foz, "a, b", foo';

Array
(
[0] => baz,\"bax\"
[1] => bay
[2] => foz
[3] => "a, b"
[4] => foo
)

Also a nice one is:
$str = 'bay, foz, "a, b", "fo\"o"';
Array
(
[0] => bay, foz, "a
[1] => b", "fo\"o"
)
Not a very robust one here.
But maybe it's OK for your data, it all depends how much you know for sure
about that.

Grtz,
--
Rik Wasmus
May 31 '06 #4
Rik wrote:


I hate to be the bearer of bad tidings, but it will fail on single escaped
\":

$str = '"baz,\"bax", bay, foz, "a, b", "foo';
$expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
$results=preg_split($expr,trim($str));
$res = preg_replace("/^\"(.*)\"$/","$1",$results);
print_r($res);

Array
(
[0] => "baz
[1] => \"bax"
[2] => bay
[3] => foz
[4] => "a, b"
[5] => foo
)

Properly nested, it can handle it:
$str = '"baz,\"bax\"", bay, foz, "a, b", foo';

Array
(
[0] => baz,\"bax\"
[1] => bay
[2] => foz
[3] => "a, b"
[4] => foo
)

Also a nice one is:
$str = 'bay, foz, "a, b", "fo\"o"';
Array
(
[0] => bay, foz, "a
[1] => b", "fo\"o"
)
Not a very robust one here.
But maybe it's OK for your data, it all depends how much you know for sure
about that.

Grtz,
--
Rik Wasmus


Indeed, that is correct. I'm going to have to chcek out my data and see
if it'll work. Do you happen to know if fgetcsv() properly handle the
single " ?

May 31 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Daniel | last post by:
I've been searching the net and Google news groups for a preg_match expression that will return true on strings containing (uppercase and lowercase) characters of A-Z, 0-9 and for instance Swedish...
2
by: Muumac | last post by:
I have problem with large textfiles! When I load over 4MB xml and then try to preg_match something in this I get always FALSE! I have <File>....</File> tags in XML. Between tags is files contents...
22
by: stoppal | last post by:
need to extract all text between the following strings, but not include the strings. "<!-- #BeginEditable "Title name" -->" "<p align="center">#### </p>" I am using preg_match(????, $s,...
9
by: Dr. StrangeLove | last post by:
Greetings, Let say we want to split column 'list' in table lists into separate rows using the comma as the delimiter. Table lists id list 1 aa,bbb,c 2 e,f,gggg,hh 3 ii,kk 4 m
4
by: Vagabond Software | last post by:
Apparently, the Split method handles consecutive tabs as a single delimiter. Does anyone have any suggestions for handling consecutive tabs? I am reading in text files that contain lines of...
15
by: Fariba | last post by:
Hello , I am trying to call a mthod with the following signature: AddRole(string Group_Nam, string Description, int permissionmask); Accroding to msdn ,you can mask the permissions using...
4
by: Yandos | last post by:
Hi all, I'd like to work with a binary file.... I read the whole file into variable (it conatains binary data from 00-FF): $fp=fopen($cfg,"r"); $content=fread($fp,filesize($cfg));...
3
by: Sam Waller | last post by:
I need a regular expression for preg_match to find all of the strings between '>' and '<' from html. Eg. 1. <TD><FONT SIZE='2'>XXX</FONT></TD> 2. <TD><FONT SIZE='2'><A...
13
by: chadsspameateremail | last post by:
I might have found a problem with how preg_match works though I'm not sure. Lets say you have a regular expression that you want to match a string of numbers. You might write the code like this:...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.