将伪XML标记解析为数组
问题描述:
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 ?
我有以下字符串: p>
$ input ='[ gallery ids =“1151,1150,1149,1148,1147”name =“ponny”]';
code> pre>
我需要将其解析为数组,所以需要 输出应如下所示: p>
$ output = array(
'ids'=>'1151,1150,1149,1148,1147',
'name'= >'ponny'
);
code> pre>
伪标记名称 gallery code>将被忽略。 p>
在PHP中执行此操作的最有效方法是什么? p>
div>
答
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.