假设我有以下字符串$shortcode:
content="my temp content" color="blue"
我想把它转换成这样的数组
array("content"=>"my temp content", "color"=>"blue")
如何使用explosion来实现?或者,我需要某种正则表达式吗?如果我使用
explode(" ", $shortcode)
将创建一个元素数组,包括属性内的元素;如果我使用
explode("=", $shortcode)
最好的方法是什么?
是否有效?这是基于我在之前的评论中链接的例子:
<?php
$str = 'content="my temp content" color="blue"';
$xml = '<xml><test '.$str.' /></xml>';
$x = new SimpleXMLElement($xml);
$attrArray = array();
// Convert attributes to an array
foreach($x->test[0]->attributes() as $key => $val){
$attrArray[(string)$key] = (string)$val;
}
print_r($attrArray);
?>
也许正则表达式不是最好的选择,但你可以尝试:
$str = 'content="my temp content" color="blue"';
$matches = array();
preg_match('/(.*?)="(.*?)" (.*?)="(.*?)"/', $str, $matches);
$shortcode = array($matches[1] => $matches[2], $matches[3] => $matches[4]);
在给$shortcode
数组赋值之前,检查所有的$matches
索引是否存在是一个很好的方法。
Regex是一种方法:
$str = 'content="my temp content" color="blue"';
preg_match_all("/('s*?)(.*)='"(.*)'"/U", $str, $out);
foreach ($out[2] as $key => $content) {
$arr[$content] = $out[3][$key];
}
print_r($arr);
您可以使用regex执行如下操作。我尽量保持正则表达式的简单。
<?php
$str = 'content="my temp content" color="blue"';
$pattern = '/content="(.*)" color="(.*)"/';
preg_match_all($pattern, $str, $matches);
$result = ['content' => $matches[1], 'color' => $matches[2]];
var_dump($result);
?>