Reply to Re: Help with regular expression

Your name:

Reply:


Posted by Pedro Graca on 09/28/24 11:37

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!

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация