Given an arbitrary string “abcdefg[hijk]” how can I extract the text before “[” and the text between “[” and “]” ? So I want “abcdefg” stored in some variable and “hjik” stored in another.
Either use regular expressions, or a combination of [d-php]strpos[/d-php] and [d-php]substr[/d-php]. Do a strpos() for the first [, and do a substr() to that character, and then do a substr() from the [ character to the strpos() of the ] character.
the regexp in php might be something like
preg_match_all(’/([^[]
]+)[([^[]
]+)]/’, $yourString, $resultArray, PREG_SET_ORDER);
this will find all instances and put them into the $resultArray array.
each element in the $resultArray will contain another array - [0] = the full string match (eg “abcdefg[hijk]”), [1] = the first part of the string (eg “abcdefg”), and [2] = the bit in the braces (eg “hjik”)
so, for example, for the first match
$resultArray[0][0] = “abcdefg[hijk]”
$resultArray[0][1] = “abcdefg”
$resultArray[0][2] = “hijk”
I recommend you use substr and strpos; I suspect it’ll be an order of magnitude faster.
Awww but i just discovered regular expressions and Im all excited about em
Regular expressions are great, but for a task this simple, it’d be silly to use them.