Tuesday, July 31, 2012

lookbehind regex in PHP

Today, I was facing a problem how to split something like following text
a="Some Text" b="Some more Text" c="Even more text about \" this text\"" d="aaaaaaa"
into array, into pairs key => value. I couldn't just use explode(), because spaces could be inside the quotes..

After a little searching, I founded that solution lies in lookbehind regular expressions.. Nifty things ^_^

This
/(?<![\\\|=])\" /
expressions would split it into following array:
array (
  0 => 'a="Some Text',
  1 => 'b="Some more Text',
  2 => 'c="Even more text about \" this text\"',
  3 => 'd="aaaaaaa"',
)
so exactly what we wanted :)

No comments:

Post a Comment