php - exploding a string using a regular expression -


i have string below (the letters in example numbers or texts , either uppercase or lowercase or both. if value sentence, should between single quotations):

$string="a,b,c,(d,e,f),g,'h, j.',k"; 

how can explode following result?

array([0]=>"a",[1]=>"b",[2]=>"c",[3]=>"(d,e,f)",[4]=>"g",[5]=>"'h,i j'",[6]=>"k") 

i think using regular expressions fast clean solution. idea?

edit: have done far, slow strings having long part between parenthesis:

$separator="*"; // whatever not used in string $pattern="'[^,]([^']+),([^']+)[^,]'"; while(ereg($pattern,$string,$regs)){     $string=ereg_replace($pattern,"'\\1$separator\\2'",$string); }  $pattern="\(([^(^']+),([^)^']+)\)"; while(ereg($pattern,$string,$regs)){     $string=ereg_replace($pattern,"(\\1$separator\\2)",$string); }  return $string; 

this, replace commas between parenthesis. can explode commas , replace $separator original comma.

you can job using preg_match_all

$string="a,b,c,(d,e,f),g,'h, j.',k";  preg_match_all('~\'[^\']++\'|\([^)]++\)|[^,]++~', $string,$result); print_r($result[0]); 

explanation:

the trick match parenthesis before ,

~          pattern delimiter ' [^']       charaters not single quote ++         1 or more time in [possessive][1] mode ' |          or \([^)]++\) same parenthesis |          or [^,]       characters not comma ++ ~ 

if have more 1 delimiter quotes (that same open , close), can write pattern this, using capture group:

$string="a,b,c,(d,e,f),g,'h, j.',k,°l,m°,#o,p#,@q,r@,s";  preg_match_all('~([\'#@°]).*?\1|\([^)]++\)|[^,]++~', $string,$result); print_r($result[0]); 

explanation:

(['#@°])   1 character in class captured in group 1 .*?        character 0 or more time in lazy mode  \1         group 1 content 

with nested parenthesis:

$string="a,b,(c,(d,(e),f),t),g,'h, j.',k,°l,m°,#o,p#,@q,r@,s";  preg_match_all('~([\'#@°]).*?\1|(\((?>[^()]++|(?-1)?)*\))|[^,]++~', $string,$result); print_r($result[0]); 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -