Re: Help with regular expression
- From: Pedro Graca <hexkid@xxxxxxxxxxx>
- Date: 15 Jan 2006 22:17:04 GMT
Tony Marston wrote:
> I am seeking help with a regular expression that will split a string into
> several parts with ',' (comma) as the separator, but NOT where the separator
> is enclosed in parentheses. For example, take the string "field1,
> CONCAT(field2,' ', field3) as field23, field4". I would like to be able to
> split this into the following:
> [0] field1
> [1] CONCAT(field2,' ', field3) as field23
> [2] field4
Can it happen that you will have nested parenthesis? :-)
Would you consider dumping preg_* function and parsing the string?
<?php
function parse_split_comma_ignore_paren($text) {
$retval = array();
$paren = 0;
$last_index = 0;
for ($index = 0; $index < strlen($text); ++$index) {
if ($text{$index} == '(') {++$paren; continue;}
/* assumes $paren will never be negative */
if ($text{$index} == ')') {--$paren; continue;}
if ($paren) continue;
if ($text{$index} == ',') {
$retval[] = trim(substr($text, $last_index, $index-$last_index));
$last_index = $index + 1;
}
}
$retval[] = trim(substr($text, $last_index));
return $retval;
}
$s = 'field1, CONCAT(field2, \' \', field3) as field23, field4,1,,3,4';
$parts = parse_split_comma_ignore_paren($s);
print_r($parts);
?>
--
Mail to my "From:" address is readable by all at http://www.dodgeit.com/
== ** ## !! ------------------------------------------------ !! ## ** ==
TEXT-ONLY mail to the whole "Reply-To:" address ("My Name" <my@address>)
may bypass my spam filter. If it does, I may reply from another address!
.
- References:
- Help with regular expression
- From: Tony Marston
- Help with regular expression
- Prev by Date: Re: How do I do date math on 'mm/dd/yyyy'? Example: 10 years earlier than today.
- Next by Date: Re: PHP sessions - user login webpage - preventing autologout due to inactivity
- Previous by thread: Help with regular expression
- Next by thread: Re: Help with regular expression
- Index(es):
Relevant Pages
|