I have following string:
$input = '[gallery ids="1151,1150,1149,1148,1147" name="ponny"]';
I need to parse it into an array, so desired output should looks like:
$output = array(
'ids' => '1151,1150,1149,1148,1147',
'name' => 'ponny'
);
Pseudo tag name gallery
will be ignored.
What is the most efficient way to do this in PHP ?
I don't know how efficient it is, but you could just turn the input into XML:
$input = '[gallery ids="1151,1150,1149,1148,1147" name="ponny"]';
$xml = str_replace( array( '[', ']' ), array( '<', ' />' ), $input );
var_dump( new SimpleXMLElement( $xml ) );
As simplest solution you can extract values between quotes
$input = '[gallery ids="1151,1150,1149,1148,1147" name="ponny"]';
preg_match_all('/\"([^\"]*?)\"/', $input, $matches);
$output = array(
'ids' => $matches[1][0],
'name' => $matches[1][1]
);
The output of var_dump($output)
is
array (size=2)
'ids' => string '1151,1150,1149,1148,1147' (length=24)
'name' => string 'ponny' (length=5)
$idsStart=strpos('ids',$input);
$idsValueStart=strpos('"',$input,$idsStart);
$idsValueEnd=strpos('"',$input,$idsValueStart);
$ids=substr($input,$idsValueStart,$idsValueEnd-$idsValueStart);
$nameStart=strpos('name',$input);
$nameValueStart=strpos('"',$input,$nameStart);
$nameValueEnd=strpos('"',$input,$nameValueStart);
$name=substr($input,$nameValueStart,$nameValueEnd-$nameValueStart);
$output=array();
$output[]=$ids;
$output[]=$name;
not terribly efficient looking, but if the order of the variables in the gallery array changes it should still give you the right answer.