Re: preg_match and delimited strings



Rik wrote:
siromega@xxxxxxxxx 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!

.



Relevant Pages